Reputation: 2661
Maybe some already asked this but I didn't find it and I wanted to know how to embed variables into a string in Python. I usually do it like this:
print('Hi, my name is %s and my age is %d' %(name, age))
But sometimes is confusing and with ruby it would be like this
puts('Hi, my name is #{name} and my age is #{age}')
Is there any way to do in Python like I to it in Ruby?
Upvotes: 1
Views: 10105
Reputation: 1122002
From Python 3.6 onwards, you can use an Formatting string literal (aka f-strings), which takes any valid Python expression inside {...}
curly braces, followed by optional formatting instructions:
print(f'Hi, my name is {name} and my age is {age:d}')
Here name
and age
are both simple expressions that produce the value for that name.
In versions preceding Python 3.6, you can use str.format()
, paired with either locals()
or globals()
:
print('Hi, my name is {name} and my age is {age}'.format(**locals()))
As you can see the format is rather close to Ruby's. The locals()
and globals()
methods return namespaces as a dictionary, and the **
keyword argument splash syntax make it possible for the str.format()
call to access all names in the given namespace.
Demo:
>>> 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
Note however that explicit is better than implicit and you should really pass in name
and age
as arguments:
print('Hi, my name is {name} and my age is {age}'.format(name=name, age=age)
or use positional arguments:
print('Hi, my name is {} and my age is {}'.format(name, age))
Upvotes: 9
Reputation: 101959
An alternative way that uses exactly Ruby's syntax for the format string:
import string
class RubyTemplate(string.Template):
delimiter = '#'
Used as:
>>> 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'
You can then create a function such as:
def print_template(template, vars):
print(RubyTemplate(template).substitute(**vars))
And use it as:
>>> print_template('Hi, my name is #{name} and my age is #{age}', locals())
Hi, my name is John Doe and my age is 42
On a side note: even python's %
allow this kind of interpolation:
>>> 'Hi, my name is %(name)s and my age is %(age)d' % locals()
'Hi, my name is John Doe and my age is 42'
Upvotes: 2
Reputation: 1178
You can also use:
dicta = {'hehe' : 'hihi', 'haha': 'foo'}
print 'Yo %(hehe)s %(haha)s' % dicta
Upvotes: 3
Reputation: 9323
str.format
is the new way to do it, but this also works:
print('Hi, my name is %(name)s and my age is %(age)d' % {
'name': name,
'age': age,
})
Which is really the same as this, if the variables already exist:
print('Hi, my name is %(name)s and my age is %(age)d' % locals())
Upvotes: -1