在 f-string 中使用大括号 {} 来表示占位符时,如果要在字符串中嵌套大括号,应该使用双大括号 {{}} 来表示

在 f-string 中使用大括号 {} 来表示占位符时,如果要在字符串中嵌套大括号,应该使用双大括号 { {}} 来表示

name = 'Tom'

print(f'my name is {name}')
# my name is Tom

print(f'my name is {
   
   {
   
   {name}}}')
# my name is {Tom}

channelCode ="A"
dataCode =  "B"
print(f'[{
   
   {"channelCode":{channelCode},"dataCode":{dataCode}]}}')
输出[{"channelCode":A,"dataCode":B]}

在 Python 中,如果要在字符串中表示大括号 {},可以使用双大括号 { {}} 来进行转义。因为单独的一个大括号在字符串中会被解析为占位符,因此需要使用两个大括号来表示一个大括号

# 使用双大括号转义大括号
str1 = "This is a pair of double braces: {
   
   {}}"
print(str1)    # 输出 This is a pair of double braces: {
   
   {}}


# 在使用 format 方法时也可以使用双大括号进行转义
str2 = "The answer is: {}"
result = str2.format("{
   
   {}}")   # 使用双大括号来代表一个大括号
print(result)    # 输出 The answer is: {}

# 如果不进行转义,会出现语法错误
#str3 = "The answer is: {}"
#result = str3.format("{}")
#print(result)    # 报错:ValueError: Single '}' encountered in format string


channelCode = "A"
dataCode = "B"

data = '[{
   
   {"channelCode":{},"dataCode":{}]}}'.format(channelCode, dataCode)
print(data)

str1 = "This is a pair of double braces: {
   
   {}}"
print(str1)

D:\MC\venv\Scripts\python.exe D:/MC/test05.py
[{"channelCode":A,"dataCode":B]}
This is a pair of double braces: {
   
   {}}

猜你喜欢

转载自blog.csdn.net/weixin_42550871/article/details/130242141
今日推荐