Python中的变量插值 [英] Variable interpolation in Python

查看:56
本文介绍了Python中的变量插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

在 PHP 中可以这样写:

$fruit = '梨';print("嘿,$fruit!");

但在 Python 中是:

fruit = '梨'打印(嘿,{0}!".格式(水果))

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

获得推荐人的奖励积分

解决方案

你现在的做法是 Pythonic 的做法.您还可以使用 locals 字典.像这样:

<预><代码>>>>水果 = '梨'>>>打印(嘿,{水果}".格式(**locals()))嘿,梨

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

Possible Duplicate:
Unpythonic way of printing variables in Python?

In PHP one can write:

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

But in Python it's:

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?

Bonus points for anyone who gets the reference

解决方案

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

>>> 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.

这篇关于Python中的变量插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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