I'm discovering possibilities of string formatting with .format( ) method in Python 3 but i raised an error that i do not understand.
So, why the following line is ok [wich let me think that "0" can be used exactly like the argument passed to format()]:
s = 'First letter of {0} is {0[0]}'.format("hello")
#gives as expected: 'First letter of hello is h'
but not this one [applying a method or a function to 0 in {0} doesn't work?]:
s = '{0} becomes {0.upper()} with .upper() method'.format("hello")
raising the following error:
AttributeError: 'str' object has no attribute 'upper()'
Why the raised error says i've used upper as an attribute and not as a method? And is there another way to do it than:
s = '{} becomes {} with .upper() method'.format("hello","hello".upper())
#gives as expected: 'hello becomes HELLO with .upper() method'
Thanks!
strdoes have a.upper()attribute - Chris_Rands()in an attribute error unless those characters are part of the attribute name. The actual attribute that does exist on thestrobject is namedupper. Trygetattr(str, 'upper()')andgetattr(str, 'upper'). The()call expression is normally applied to the result of the attribute lookup. - Martijn Pieters♦