Python中的变量替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24447287/
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-19 04:37:41  来源:igfitidea点击:

Variable Substitution in Python

pythonstringweb.py

提问by yrk

So I'm working with Web.py and I have following code:

所以我正在使用 Web.py 并且我有以下代码:

check = db.select('querycode', where='id=$id', vars=locals())[0]

Which works fine, it substitutes $id with the variable. But in this line it does not work:

哪个工作正常,它将 $id 替换为变量。但在这一行它不起作用:

web.sendmail('[email protected]', "[email protected]", 'Subject', 'Hello $name')

What do I wrong and how could it work. Also did I get the concept right: A $-sign substitutes the variable?

我做错了什么,它是如何工作的。我的概念是否正确:$ 符号替代变量?

采纳答案by merlin2011

Python does not in general do PHP-style variable interpolation.

Python 通常不做 PHP 风格的变量插值。

What you are seeing in the first statement is a special feature of db.selectwhich picks the variable values out of the local variables in the context of the caller.

您在第一条语句中看到的是一个特殊功能,db.select它在调用者的上下文中从局部变量中挑选变量值。

If you want to substitute in the variable in your second line, you will have to do it manually with one of the ways Python provides. Here is one such way.

如果要替换第二行中的变量,则必须使用 Python 提供的一种方法手动执行。这是一种这样的方式。

web.sendmail('[email protected]', "[email protected]", 'Subject', 'Hello %s' % name)

Here is another way.

这是另一种方式。

web.sendmail('[email protected]', "[email protected]", 'Subject', 'Hello {0}'.format(name))

The first option is documented in String Formatting operations.

第一个选项记录在字符串格式操作中

See the documentation for str.formatand Format String Syntaxfor more details on the second option.

有关第二个选项的更多详细信息,请参阅str.formatFormat String Syntax的文档。

回答by shx2

@merlin2011's answer explains it best.

@merlin2011 的回答解释得最好。

But just to complement it, since you're trying to substitute by variable name, python also supports the following form of "substitution" (or string formatting):

但只是为了补充它,因为您尝试通过变量 name替换,python 还支持以下形式的“替换”(或字符串格式):

'Hello %(name)s' % locals()

Or to limit the namespace:

或者限制命名空间:

'Hello %(name)s' % {'name': name}


EDIT Since python 3.6, variable substitution is a done natively using f-strings. E.g.,

编辑从 python 3.6 开始,变量替换是使用f-strings本地完成的。例如,

print( f'Hello {name}' )