Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python do variable interpolation similar to "string #{var}" in Ruby?

In Python, it is tedious to write:

print "foo is" + bar + '.' 

Can I do something like this in Python?

print "foo is #{bar}."

like image 579
mko Avatar asked Aug 03 '12 02:08

mko


People also ask

Is there string interpolation in Python?

Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f . This new way of formatting strings is powerful and easy to use. It provides access to embedded Python expressions inside string constants.

Which character should be used for string interpolation in Python?

There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator.

What is string interpolation better known as?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.

How does string interpolation perform?

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.


2 Answers

Python 3.6+ does have variable interpolation - prepend an f to your string:

f"foo is {bar}" 

For versions of Python below this (Python 2 - 3.5) you can use str.format to pass in variables:

# Rather than this: print("foo is #{bar}")  # You would do this: print("foo is {}".format(bar))  # Or this: print("foo is {bar}".format(bar=bar))  # Or this: print("foo is %s" % (bar, ))  # Or even this: print("foo is %(bar)s" % {"bar": bar}) 
like image 93
Sean Vieira Avatar answered Sep 20 '22 14:09

Sean Vieira


Python 3.6 will have has literal string interpolation using f-strings:

print(f"foo is {bar}.") 
like image 32
AXO Avatar answered Sep 18 '22 14:09

AXO