Python 2 中的格式化字符串文字 [英] Formatted String Literals in Python 2

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

问题描述

在 Python 2.7 中编写模块时,我需要一种方法

While writing a module in Python 2.7 I had the need of a way for doing

name = "Rodrigo"
age = 34
print f"Hello {name}, your age is {age}".format()

虽然我知道我可以做到:

although I know I could just do:

print "Hello {name}, your age is {age}".format(name=name, age=age)

format() 将在变量 nameage 的范围内查找,将它们转换为字符串(如果可能)并粘贴到消息.我发现这已经在 Python 3.6+ 中实现,称为 Formatted String文字.所以,我想知道(在谷歌上找不到)是否有人已经为 Python 2.7 开发了类似的方法

format() would look in the scope for variables name and age, cast them to a string (if possible) and paste into the message. I've found that this is already implemented in Python 3.6+, called Formatted String Literals. So, I was wondering (couldn't find it googling) if anyone has made an approach to something similar for Python 2.7

推荐答案

你可以通过结合内置的 locals 函数和 来尝试 hackish 的做事方式>format 字符串上的方法:

You can try the hackish way of doing things by combining the builtin locals function and the format method on the string:

foo = "asd"
bar = "ghi"

print("{foo} and {bar}".format(**locals())

这篇关于Python 2 中的格式化字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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