Raf*_*ini 47 python local-variables string-formatting locals
关于使用以下模式是否有任何缺点,警告或不良做法警告?
def buildString(user, name = 'john', age=22):
userId = user.getUserId()
return "Name: {name}, age: {age}, userid:{userId}".format(**locals())
Run Code Online (Sandbox Code Playgroud)
我有一个非常重复的字符串生成代码来编写并且很想使用它,但是关于使用的东西locals()
让我感到不舒服.这有意外行为的危险吗?
编辑:上下文
我发现自己经常写下这样的东西:
"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)
Run Code Online (Sandbox Code Playgroud)
Jac*_*ose 29
从Python 3.6.0开始,现在有一种官方方法可以做到这一点:格式化字符串文字.
它的工作原理如下:
f'normal string text {local_variable_name}'
Run Code Online (Sandbox Code Playgroud)
例如,而不是这些:
"hello %(name)s you are %(age)s years old" % locals()
"hello {name}s you are {age}s years old".format(**locals())
"hello {name}s you are {age}s years old".format(name=name, age=age)
Run Code Online (Sandbox Code Playgroud)
这样做:
f"hello {name}s you are {age}s years old"
Run Code Online (Sandbox Code Playgroud)
这是官方的例子:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
参考:
归档时间: |
|
查看次数: |
13603 次 |
最近记录: |