简体   繁体   中英

Formatting a concatenated python string

It seems as if string formatting doesn't work on concatenated strings. With concatenation the place holder gets printed literally:

>>> print("{}" + " OK".format("Text"))
{} OK

However, without concatenation the format gets printed as it should:

>>> print("{} OK".format("Text"))
Text OK

The same problem occurs with old-style %-formatting.

If I have a long multi-line string where I would like to concatenate a string that should be formatted, what is the recommended way?

You were attempting to perform the "format" operation prior to doing the concatenation. You can fix the precedence of operations by using parentheses:

>>> the_string = ("{}" + " OK").format("Text")
>>> print(the_string)
Text OK

您只需要修复括号:

print(("{}" + " OK").format("Text"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM