gpt4 book ai didi

string-formatting - Python : replacing several %s with the same variable 中的输出格式

转载 作者:IT老高 更新时间:2023-10-28 21:14:33 25 4
gpt4 key购买 nike

我正在尝试维护/更新/重写/修复一些看起来有点像这样的 Python:

variable = """My name is %s and it has been %s since I was born.
My parents decided to call me %s because they thought %s was a nice name.
%s is the same as %s.""" % (name, name, name, name, name, name)

整个脚本都有这样的小片段,我想知道是否有更简单(更 Pythonic?)的方式来编写这段代码。我发现了一个这样的例子,它把同一个变量替换了大约 30 次,感觉很丑。

解决(在我看来)丑陋的唯一方法是把它分成很多小块吗?

variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)

最佳答案

改用字典。

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

format 带有明确的编号。

var = '{0} {0} {0}'.format('look_at_meeee')

好吧,或者 format 带有命名参数。

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')

关于string-formatting - Python : replacing several %s with the same variable 中的输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6982949/

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