Reputation: 1391
When attempting to reformat {r[Name]}
to uppercase (originally it is titlecase: James
)
string = 'text {r[Name]} data'.format(r=row)
string = 'text {r[Name].uppercase()} data'.format(r=row)
I get the traceback: AttributeError: 'str' object has no attribute 'uppercase'
Any ideas? Many thanks SMNALLY
Upvotes: 1
Views: 256
Reputation: 365835
This is because strings don't have a method named uppercase
, exactly as the error message says.
You probably wanted upper
.
However, you can't actually call methods in a format string this way. You can access the upper
attribute (just remove the parens), but then you'll get something like 'text <built-in method upper of str object at 0x12345678> data'
, which isn't very helpful.
So, how do you do this? You don't. format
is intentionally restricted to make it harder to accidentally run arbitrary untrusted code. If you think you need a function call, that's usually a sign that you're getting too fancy and should just create an intermediate value explicitly. For example:
string = 'text {name} data'.format(name=row['Name'].upper())
Upvotes: 4