When attempting to reformat {r[Name]} to uppercase (originally it is titlecase: James)

Original code

string = 'text {r[Name]} data'.format(r=row)

Attempt

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

有帮助吗?

解决方案

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())
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top