Python 3 中的模块级别 string.upper 函数在哪里?

where is the module level string.upper function in Python 3?

如何让此代码在 3 中运行?

请注意,我不是在字符串实例级别询问 "foo".upper()

import string
try:
    print("string module, upper function:")
    print(string.upper)
    foo = string.upper("Foo")
    print("foo:%s" % (foo))
except (Exception,) as e:
    raise

2 上的输出:

string module, upper function:
<function upper at 0x10baad848>
foo:FOO

3 的输出:

string module, upper function:
Traceback (most recent call last):
  File "dummytst223.py", line 70, in <module>
    test_string_upper()
  File "dummytst223.py", line 63, in test_string_upper
    print(string.upper)
AttributeError: module 'string' has no attribute 'upper'

help(string) 也不是很有帮助。据我所知,剩下的唯一功能是 string.capwords.

注意:有点老套,但这是我的短期解决方法。

import string

try:
    _ = string.upper
except (AttributeError,) as e:
    def upper(s):
        return s.upper()
    string.upper = upper

您描述的所有 string 模块级函数已在 Python 3 中删除。Python 2 string module documentation 包含此注释:

You should consider these functions as deprecated, although they will not be removed until Python 3.

如果 Python 2 中有 string.upper(foo),则需要将其转换为 Python 中的 foo.upper() 3.