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?
Python String lower() The lower() method converts all uppercase characters in a string into lowercase characters and returns it.
Python String lower() Method The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
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.
You can translate user input to lowercase using Python's built-in "lower" string function.
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'
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With