gpt4 book ai didi

关于字符串中多个 %s 的 python

转载 作者:太空狗 更新时间:2023-10-29 19:31:42 27 4
gpt4 key购买 nike

str = 'I love %s and %s, he loves %s and %s.' 

我想用这种格式来展示

我喜欢苹果和沥青,他喜欢苹果和沥青。

请只添加两个变量,但需要一种在一个句子中使用它两次的方法。

最佳答案

使用字典:

>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
>>> s % {"x" : "apples", "y" : "oranges"}
'I love apples and oranges, he loves apples and oranges.'

或者使用更新的format函数,在 2.6 中引入:

>>> s = 'I love {0} and {1}, she loves {0} and {1}'
>>> s.format("apples", "oranges")
'I love apples and oranges, she loves apples and oranges'

注意:调用变量 str 会屏蔽内置函数 str([object]) .

关于关于字符串中多个 %s 的 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4435152/

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