gpt4 book ai didi

python - 对字符串 : are there any caveats? 使用 locals() 和 format() 方法

转载 作者:IT老高 更新时间:2023-10-28 20:34:30 30 4
gpt4 key购买 nike

关于使用以下模式是否有任何缺点、注意事项或不良做法警告?

def buildString(user, name = 'john', age=22):
userId = user.getUserId()
return "Name: {name}, age: {age}, userid:{userId}".format(**locals())

我有一个非常重复的字符串生成代码要编写并且很想使用它,但是使用 locals() 让我感到不舒服。这是否有任何意外行为的危险?

编辑:上下文

我发现自己经常写这样的东西:

"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)

最佳答案

现在有一种官方方法可以做到这一点,从 Python 3.6.0 开始:formatted string literals

它是这样工作的:

f'normal string text {local_variable_name}'

例如而不是这些:

"hello %(name) you are %(age) years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {name} you are {age} years old".format(name=name, age=age)

这样做:

f"hello {name} you are {age} years old"

这是官方的例子:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'

引用:

关于python - 对字符串 : are there any caveats? 使用 locals() 和 format() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11764900/

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