我有一个工作的 python 脚本,但 python 3 中一定有一些改变。
例如,如果我想将参数 1 转换为小写:
import string
print(string.lower(sys.argv[1]))
它说 'module' 对象没有属性 'lower'
- 好的,我明白了,string
现在是一个模块。
如果我删除导入,只写 string.lower('FOO')
,它会提示 name 'string' is not defined
。
那么将字符串转换为小写的正确方法是什么?
最佳答案
您可以使用sys.argv[1].lower()
>>> "FOo".lower()
'foo'
lower()
是字符串对象本身的一个方法。
string
模块在 Python 3 中已经改变,它不再包含与 str
对象相关的方法,它现在只包含下面提到的常量。
您也可以使用 str.lower("Mystring")
但这里没有必要,因为您可以简单地使用 "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']
关于python - Python 3 中的 string.lower,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16643166/