对字符串使用locals()和format()方法:有什么警告吗? [英] Using locals() and format() method for strings: are there any caveats?

查看:104
本文介绍了对字符串使用locals()和format()方法:有什么警告吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下模式是否有任何不利之处,警告或不良做法警告?

Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

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

我编写了一个非常重复的字符串生成代码,并试图使用它,但是关于使用locals()的某些操作使我感到不舒服.这有发生意外行为的危险吗?

I had a very repetitive string generation code to write and was tempted to use this, but something about using locals() makes me uncomfortable. Is there any danger of unexpected behavior in this?

上下文

我发现自己不断写类似的东西:

I found myself constantly writing stuff like:

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

推荐答案

从Python 3.6.0开始,现在有一种正式的方法可以做到这一点:

There is now an official way to do this, as of Python 3.6.0: formatted string literals.

它是这样的:

f'normal string text {local_variable_name}'

例如代替这些:

"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)

只需这样做:

f"hello {name}s you are {age}s 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 3.6 What's New
  • PEP 498
  • Lexical analysis description

这篇关于对字符串使用locals()和format()方法:有什么警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆