Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.lower in Python 3

I had a working python script, but something must have changed in python 3.

For example if I wanted to convert argument 1 to lowercase:

import string
print(string.lower(sys.argv[1]))

It says that 'module' object has no attribute 'lower' - OK, I understand, string is a module now.

If I remove the import, and write only string.lower('FOO'), it complains that name 'string' is not defined.

So what's the correct way to do convert a string to lowercase?

like image 870
Axarydax Avatar asked May 20 '13 05:05

Axarydax


People also ask

How do you lowercase a string in Python 3?

Python String lower() The lower() method converts all uppercase characters in a string into lowercase characters and returns it.

What does lower () do in Python?

Python String lower() Method The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.

Why is lower () not working Python?

It's because python strings are immutable. That means you can't change them in-place, just make a changed copy of it and assign it to some other variable, or itself.

Can you do input Lower () Python?

You can translate user input to lowercase using Python's built-in "lower" string function.


2 Answers

To add, while some people prefer the object-oriented way (calling the method of the str object), some may still prefer the older way -- with functions or operators. It depends also on the problem being solved. (If you do not agree, think for example about (1.5).__add__(3).)

You can easily create your own (simpler) name for the function that you need to make it more readable. You only should think about whether it will be readable (in future for you and now) for everyone:

>>> lower = str.lower
>>> lower('SoMe CaPiTaL LetTerS to Be LoWeRED')
'some capital letters to be lowered'
like image 87
pepr Avatar answered Oct 20 '22 21:10

pepr


You can use sys.argv[1].lower()

>>> "FOo".lower()
'foo'

lower() is a method of string objects itself.

string module has been changed in Python 3, it no longer contains the methods related to str objects, it now only contains the constants mentioned below.

You can also use str.lower("Mystring") but that's unnecessary here as you can simply use "Mystring".lower().

>>> import string  # Python 3
>>> dir(string)
['ChainMap', 'Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
like image 20
Ashwini Chaudhary Avatar answered Oct 20 '22 19:10

Ashwini Chaudhary