0

How do I get this code to work in 3?

Please note that I am not asking about "foo".upper() at the string instance level.

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

output on 2:

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

output on 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) wasn't very helpful either. Far as I can tell, the only function left is string.capwords.

Note: a bit hacky, but here's a my short-term workaround.

import string

try:
    _ = string.upper
except (AttributeError,) as e:
    def upper(s):
        return s.upper()
    string.upper = upper
JL Peyret
  • 10,917
  • 2
  • 54
  • 73
  • 1
    https://docs.python.org/2/library/string.html#deprecated-string-functions: "You should consider these functions as deprecated, although they will not be removed until Python 3." Use the string instance methods. – David Maze Jul 25 '18 at 23:18
  • txs. if you put it as an answer, I'll accept it. – JL Peyret Jul 25 '18 at 23:22

1 Answers1

4

All of the string module-level functions you describe were removed in Python 3. The Python 2 string module documentation contains this note:

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

If you have string.upper(foo) in Python 2, you need to convert that to foo.upper() in Python 3.

David Maze
  • 130,717
  • 29
  • 175
  • 215