Explain Codes LogoExplain Codes Logo

Is there a Python equivalent to Ruby's string interpolation?

python
f-strings
string-interpolation
python-syntax
Anton ShumikhinbyAnton Shumikhin·Nov 25, 2024
TLDR

Python does offer equivalent functionality to Ruby's string interpolation in the form of f-strings. By adding an f prefix to your string and enclosing expressions in {}, you can achieve interpolation:

user = "Alice" message = f"Hello, {user}!" # Prints: Hello, Alice!

This behavior is available in Python 3.6 and newer editions.

Traditional methods for string interpolation

Before f-strings came to the scene, Python developers often used other techniques for interpolation: the % operator, .format() method and string.Template class.

  1. Using % operator, similar to printf in C:
name = "Guido" language = "Python" print("%s created %s. Enough said." % (name, language)) # Guido created Python. Enough said.
  1. .format() offers multitude of options for precision and complex formatting:
item = "f-strings" reason = "plain awesomeness" print("I like {} because of their {}.".format(item, reason)) # I like f-strings because of their plain awesomeness.
  1. string.Template class for a more explicit substitution with $ syntax:
from string import Template t = Template('Hey, $name!') t.substitute(name='Alice') # Hey, Alice!

New kid in town: f-strings

F-strings, or formatted string literals, were introduced to offer a concise, readable, and pythonic way to embed expressions within string literal, aiming to simplify the process of interpolation.

  1. Embedding expressions:
import math radius = 5 area = f"The area of a circle with radius {radius} is {math.pi * radius ** 2:.2f}." # Nothing like calculating Pi on the fly!

Notice the :.2f in the embedded expression - this formats the output to two decimal places.

  1. Applying on complex objects:
class Developer: def __init__(self, name, language): self.name = name self.language = language dev = Developer("Alice", "Python") f"{dev.name} codes in {dev.language}." # No, it's not a magic show. Yes, it's pretty cool.
  1. Advanced usage and inlining expressions:
subtotal = 100 tax_rate = 0.05 f"Total billed amount: ${subtotal * (1 + tax_rate):.2f}" # Math + code = endless possibilities.

Enter: Interpy

If you're a fan of Ruby's interpolation or just enjoy introducing new syntax into Python files, there is a package, interpy, that allows you to use Ruby-like string interpolation in Python. Here's how to get it:

  1. Install it using pip install interpy.
  2. Add # coding: interpy at the top in your Python file.
  3. You're ready to go!
# coding: interpy user = "Alice" print "Hello, #{user}!" # Hello, Alice without even raising a sweat.

Visualization

Here's a simpe visualization between Python and Ruby string interpolation, coded as chefs serving personalized dishes:

Python Chef (🐍): "Check out your bespoke dish: f'{name} tastes {flavor}!'" Ruby Chef (💎): "Savor your tailor-made dish: '#{name} tastes #{flavor}'!"

They deliver the same result - dynamic strings with placeholders, but their syntax carries a unique flavor.

# In Python name = 'Python 3.6+' flavor = 'sweet' meal = f'{name} tastes {flavor}!' # Python 3.6+ tastes sweet! # In Ruby name = 'Ruby' flavor = 'savory' meal = "#{name} tastes #{flavor}!" # Ruby tastes savory!

Code with panache using f-strings

F-strings don’t just provide a way for developers to minimize verbosity, they pave way for cleaner and maintainable code.

Reduce repetition and verbosity

In cases where you're constructing a dynamic SQL query, f-strings come in handy to keep your code neat and maintainable:

table_name = "users" column_name = "last_login" timestamp = "2023-04-01" query = f"SELECT * FROM {table_name} WHERE {column_name} > '{timestamp}'" # SQL queries made easy peasy!

Debug delight

Debugging sessions get a breather with f-strings. Python offers a debugging shorthand that prints both the expression and its value. Just add = within the brackets:

score = 42 print(f"{score=}") # prints: score=42

Aid in dynamic formatting

F-strings ace in situations needing dynamic formatting. Say hello to real-time computed width and precision:

from math import pi precision = 3 width = 10 print(f"Value of pi: {pi:{width}.{precision}}") # Looks complicated, but it's really not!