gpt4 book ai didi

python - 字符串格式化和传递

转载 作者:行者123 更新时间:2023-12-04 10:11:10 24 4
gpt4 key购买 nike

我正在尝试格式化下面的代码,但失败了,由于大括号已经就位,因此格式化功能无法正常工作。

def in_list(line):
input = '{"word1":["one"], "word_list":{}, "bool":true}'.format(line)
print(input)

msg = ["hello", "how", "are", "you"]
in_list(msg)



Expected Output:

'{"word1":["one"], "word_list":["hello","how","are","you"], "bool":true}'

有没有办法将列表传递到句子中。请告诉我,谢谢。

最佳答案

你必须把括号加倍{{ , }}
来自 docs :

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.



您可以使用:
def in_list(line):
my_input = '{{"word1":["one"], "word_list":{0}, "bool":true}}'.format(line)
print(my_input)

msg = ["hello","how","are","you"]
in_list(msg)

# {"word1":["one"], "word_list":['hello', 'how', 'are', 'you'], "bool":true}

关于python - 字符串格式化和传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61326198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com