python - Python 3 中的 string.lower

标签 python string python-3.x

我有一个工作的 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/

相关文章:

python - 用python调用多个过程

python - 对另一个矩阵的每一列进行 Numpy 矩阵减法

Python turtle 图章在 turtle 形状的图像处理后神秘消失

python - 正则表达式字符匹配计数器

python - 按下随机键时 cv2.waitKey(0) 不等待 - OpenCV 3.1.0、Python3、Ubuntu

python - 使用 Python docx 模糊特定标题下的图像

python - Django 外键从无开始

python - 将字符串列表与字符串列表进行比较(python)

python - 为不带引号的函数获取字符串参数

c - 如何在 C 中读取 argv[1][1 - 直到字符串末尾]