【问题标题】:where is the module level string.upper function in Python 3?Python 3 中的模块级 string.upper 函数在哪里?
【发布时间】:2018-07-25 23:08:03
【问题描述】:

如何让这段代码在 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

【问题讨论】:

  • docs.python.org/2/library/…: “你应该认为这些函数已被弃用,尽管它们直到 Python 3 才会被删除。”使用字符串实例方法。
  • TXS。如果你把它作为答案,我会接受它。

标签: python-2to3


【解决方案1】:

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

您应该将这些函数视为已弃用,尽管它们在 Python 3 之前不会被删除。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2011-11-18
    • 2013-07-28
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多