简体   繁体   English

格式化串联的python字符串

[英]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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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