简体   繁体   English

Python中的变量替换

[英]Variable Substitution in Python

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. 哪个工作正常,它用变量替换$ id。 But in this line it does not work: 但是在这一行中它不起作用:

web.sendmail('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello $name')

What do I wrong and how could it work. 我有什么不对,怎么可能有用呢。 Also did I get the concept right: A $-sign substitutes the variable? 我也得到了正确的概念:$ -sign代替变量?

@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): 但只是为了补充它,因为你试图用变量名替换,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 . 编辑自python 3.6以来,变量替换是使用f-strings本地完成的。 Eg, 例如,

print( f'Hello {name}' )

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.select which 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. 如果要替换第二行中的变量,则必须使用Python提供的方法之一手动执行此操作。 Here is one such way. 这是一种这样的方式。

web.sendmail('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello %s' % name)

Here is another way. 这是另一种方式。

web.sendmail('mail@mail.mail', "tomail@tomail.tomail", 'Subject', 'Hello {0}'.format(name))

The first option is documented in String Formatting operations . 第一个选项记录在字符串格式化操作中

See the documentation for str.format and Format String Syntax for more details on the second option. 有关第二个选项的更多详细信息,请参阅str.formatFormat String Syntax的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM