Axa*_*dax 11 python string python-3.x
我有一个工作的python脚本,但在python 3中必须改变一些东西.
例如,如果我想将参数1转换为小写:
import string
print(string.lower(sys.argv[1]))
Run Code Online (Sandbox Code Playgroud)
它说'module' object has no attribute 'lower'- 好吧,我明白,string现在是一个模块.
如果我删除导入,只写string.lower('FOO'),它会抱怨name 'string' is not defined.
那么将字符串转换为小写的正确方法是什么?
Ash*_*ary 15
您可以使用 sys.argv[1].lower()
>>> "FOo".lower()
'foo'
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
它str不是string:
>>> str.lower("HELLO")
'hello'
Run Code Online (Sandbox Code Playgroud)
因此,您得到name 'string' is not defined.错误的原因是当前在调用的范围内不存在变量string.