是否有一个与Ruby的字符串插值等效的Python?

Ruby示例: html

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

对我而言,成功的Python字符串链接彷佛很冗长。 python


#1楼

import inspect
def s(template, **kwargs):
    "Usage: s(string, **locals())"
    if not kwargs:
        frame = inspect.currentframe()
        try:
            kwargs = frame.f_back.f_locals
        finally:
            del frame
        if not kwargs:
            kwargs = globals()
    return template.format(**kwargs)

用法: git

a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found

PS:性能可能有问题。 这对于本地脚本颇有用,而不对生产日志有用。 github

重复的: ruby


#2楼

你也能够有这个 this

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings


#3楼

我开发了interpy软件包,该软件包可在Python启用字符串插值

只需经过pip install interpy进行pip install interpy 。 而后,在文件开头添加# coding: interpy# coding: interpy

例:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."

#4楼

按照PEP 498的规定,Python 3.6包含字符串插值。 您将能够执行如下操做:

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')

请注意,我讨厌海绵宝宝,因此写这篇文章有点痛苦。 :)


#5楼

对于旧的Python(在2.4上测试),最佳解决方案指明了方向。 你能够这样作:

import string

def try_interp():
    d = 1
    f = 1.1
    s = "s"
    print string.Template("d: $d f: $f s: $s").substitute(**locals())

try_interp()

你获得

d: 1 f: 1.1 s: s
相关文章
相关标签/搜索