简体   繁体   English

如何在格式化的 python 字符串中允许“{”或“}”字符

[英]How to allow '{' or '}' characters in a formatted python string

I need to print out a string similar to: "Field1: {Bob} Field2: {value}" Where the 1st field is constant, but the second field is formatted from some variable.我需要打印出一个类似于: "Field1: {Bob} Field2: {value}"的字符串,其中第一个字段是常量,但第二个字段是从某个变量格式化的。 I tried using a line like this:我尝试使用这样的行:

field_str = "Field1: {Bob} Field2: {}".format(val)

But I get the error:但我得到了错误:

 KeyError: 'Bob'

I'm pretty sure this is because the '{' and '}' characters in the string are being interpreted as something that needs to be formatted even though I want the string to contain those values.我很确定这是因为字符串中的“{”和“}”字符被解释为需要格式化的东西,即使我希望字符串包含这些值。 This is part of a much larger string, so I would prefer to not manually concatenate the strings together, but I would be ok with somehow adding format characters or something to get it to ignore the values that are inside "{}" in the string.这是一个更大的字符串的一部分,所以我不想手动将字符串连接在一起,但我可以通过某种方式添加格式字符或其他东西让它忽略字符串中“{}”内的值.

Is there any way to indicate that a '{' or '}' character is not intended for formatting in a string?有什么方法可以表明 '{' 或 '}' 字符不用于格式化字符串?

Use the double {{}} with python string formating f"...".将双{{}}与 python 字符串一起使用,格式为 f"..."。

val = 2

field_str = f"Field1: {{Bob}} Field2: {val}"
print(field_str)

Output: Output:

Field1: {Bob} Field2: 2

You may also pre-format the Bob value.您还可以预先格式化Bob值。 For example例如

val = 2
field1 = '{Bob}'

field_str = f"Field1: {field1} Field2: {val}"

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

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