如何使此代码在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