Python中的变量插值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3542714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:39:07  来源:igfitidea点击:

Variable interpolation in Python

pythonstring

提问by Aillyn

Possible Duplicate:
Unpythonic way of printing variables in Python?

可能的重复:
在 Python 中打印变量的 Unpythonic 方式?

In PHP one can write:

在 PHP 中可以这样写:

$fruit = 'Pear';
print("Hey, $fruit!");

But in Python it's:

但在 Python 中它是:

fruit = 'Pear'
print("Hey, {0}!".format(fruit))

Is there a way for me to interpolate variables in strings instead? And if not, how is this more pythonic?

有没有办法让我在字符串中插入变量?如果没有,这如何更像 pythonic?

Bonus points for anyone who gets the reference

获得参考的任何人的奖励积分

采纳答案by Sam Dolan

The way you're doing it now is a pythonic way to do it. You can also use the localsdictionary. Like so:

你现在这样做的方式是一种pythonic的方式。您也可以使用locals字典。像这样:

>>> fruit = 'Pear'
>>> print("Hey, {fruit}".format(**locals()))
Hey, Pear

Now that doesn't look very pythonic, but it's the only way to achieve the same affect you have in your PHP formatting. I'd just stick to the way you're doing it.

现在这看起来不是很 Pythonic,但它是实现与 PHP 格式相同的影响的唯一方法。我只是坚持你的方式。

回答by kloffy

Something like this should work:

这样的事情应该工作:

"%(fruit)s" % locals()

回答by knutin

The closest you can get to the PHP behaviour is and still maintaining your Python-zen is:

最接近 PHP 行为并且仍在维护 Python-zen 的是:

print "Hey", fruit, "!"

print will insert spaces at every comma.

print 将在每个逗号处插入空格。

The more common Python idiom is:

更常见的 Python 习语是:

print "Hey %s!" % fruit

If you have tons of arguments and want to name them, you can use a dict:

如果您有大量参数并想命名它们,您可以使用字典:

print "Hey %(crowd)s! Would you like some %(fruit)s?" % { 'crowd': 'World', 'fruit': 'Pear' }

回答by Matt Anderson

A slight adaptation from the NamespaceFormatter example in PEP-3101:

稍微改编自PEP-3101 中的 NamespaceFormatter 示例:

import string

class NamespaceFormatter(string.Formatter):
  def __init__(self, namespace={}):
      super(NamespaceFormatter, self).__init__()
      self.namespace = namespace

  def get_value(self, key, args, kwds):
      if isinstance(key, str):
          try:
              # Check explicitly passed arguments first
              return kwds[key]
          except KeyError:
              return self.namespace[key]
      else:
          super(NamespaceFormatter, self).get_value(key, args, kwds)

fmt = NamespaceFormatter(globals())
fruit = 'Pear'

print fmt.format('Hey, {fruit}!')

for:

为了:

Hey, Pear!

回答by leoluk

Don't do it. It is unpythonic. As example, when you add translations to your app, you can't longer control which variables are used unless you check all the translations files yourself.

不要这样做。它是非pythonic的。例如,当您向应用程序添加翻译时,除非您自己检查所有翻译文件,否则您无法再控制使用哪些变量。

As example, if you change a local variable, you'll have to change it in all translated strings too.

例如,如果您更改了一个局部变量,您也必须在所有已翻译的字符串中更改它。