Python中嵌入变量的字符串

时间:2013-05-14 21:15:46

标签: python string variables string-formatting

也许有些人已经问过这个,但我没有找到它,我想知道如何在Python中将变量嵌入到字符串中。我通常这样做:

print('Hi, my name is %s and my age is %d' %(name, age))

但有时令人困惑,而且红宝石就像这样

puts('Hi, my name is #{name} and my age is #{age}')

有没有办法在Python中像我一样在Ruby中做什么?

4 个答案:

答案 0 :(得分:6)

从Python 3.6开始,您可以使用Formatting string literal(又名 f-strings ),它在{...}花括号中使用任何有效的Python表达式,然后是可选格式指令:

print(f'Hi, my name is {name} and my age is {age:d}')

此处nameage都是生成该名称值的简单表达式。

在Python 3.6之前的版本中,您可以使用str.format(),与locals()globals()配对:

print('Hi, my name is {name} and my age is {age}'.format(**locals()))

正如您所看到的,格式与Ruby的格式非常接近。 locals()globals()方法将名称空间作为字典返回,**关键字参数splash语法使str.format()调用可以访问给定名称空间中的所有名称。

演示:

>>> name = 'Martijn'
>>> age = 40
>>> print('Hi, my name is {name} and my age is {age}'.format(**locals()))
Hi, my name is Martijn and my age is 40

但请注意,显式优于隐式,您应该将nameage作为参数传递:

print('Hi, my name is {name} and my age is {age}'.format(name=name, age=age)

或使用位置参数:

print('Hi, my name is {} and my age is {}'.format(name, age))

答案 1 :(得分:3)

您也可以使用:

dicta = {'hehe' : 'hihi', 'haha': 'foo'}
print 'Yo %(hehe)s %(haha)s' % dicta

答案 2 :(得分:0)

使用Ruby语法完全使用格式字符串的替代方法:

import string
class RubyTemplate(string.Template):
    delimiter = '#'

用作:

>>> t = RubyTemplate('Hi, my name is #{name} and my age is #{age}')
>>> name = 'John Doe'
>>> age = 42
>>> t.substitute(**locals())
'Hi, my name is John Doe and my age is 42'

然后您可以创建一个函数,例如:

def print_template(template, vars):
    print(RubyTemplate(template).substitute(**vars))

并将其用作:

>>> print_template('Hi, my name is #{name} and my age is #{age}', locals())
Hi, my name is John Doe and my age is 42

旁注:即使是python的%也允许这种插值:

>>> 'Hi, my name is %(name)s and my age is %(age)d' % locals()
'Hi, my name is John Doe and my age is 42'

答案 3 :(得分:-1)

str.format是新的方式,但这也有效:

print('Hi, my name is %(name)s and my age is %(age)d' % {
   'name': name,
   'age': age,
})

如果变量已经存在,那么这与此真的相同:

print('Hi, my name is %(name)s and my age is %(age)d' % locals())