【发布时间】: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