문제

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