是否有一個與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
相關文章
相關標籤/搜索