StmWtr StmWtr - 1 year ago 63
Python Question

Python: Printing value after .upper

I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location.

Why does it print the operation instead of the result?

x = 'bacon'
x = x.upper
print x

<built-in method upper of str object at 0x02A95F60>

Answer Source

Everything in Python is an object, including functions and methods. x.upper is the upper attribute of x, which happens to be a function object. x.upper() is the result of trying to call that attribute as a function, so you are trying to do

print x.upper()

As an aside, you can try to call any object in Python, not just functions. It will not always work, but the syntax is legitimate. You can do

x = 5

or even


but of course you will get an error (the exact same one in both cases). However, you can actually call objects as functions as long as they define a __call__ method (as normal functions do). Your example can actually be rewritten as

print x.upper.__call__()