1

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?

4 Answers 4

9

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))
3

You can also use:

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

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'
4
  • Actually this looks more complicated, I'm looking for something simple. Commented May 15, 2013 at 2:02
  • @AndresOrozco I never stated this was simpler, I just wanted to provide an alternative that matches ruby's "template syntax".
    – Bakuriu
    Commented May 15, 2013 at 5:09
  • Yeah, But I was asking for something simple, like in Ruby. Commented May 15, 2013 at 15:09
  • @AndresOrozco The short answer for your question, which stated more clearly is "does python provide automatic string interpolation?", the answer is no and there is no way to do that. You can use str.format, use %(name)s but you must always pass explicitly the objects to interpolate. The only way to do automatic string interpolation is to hack the bytecode of functions to automatically insert the calls to str.format, but you probably cannot guarantee it will work correctly most of the time.
    – Bakuriu
    Commented May 15, 2013 at 17:41
-1

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())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.