Introduction to String Formatting and Interpolation

Welcome aboard! Today, we're venturing into the world of string formatting and interpolation in Python. These operations enable dynamic string construction, which streamlines coding in Python. Picture yourself compiling daily astronaut logs; these techniques allow you to create a template and fill in the variable part each time. In this lesson, we'll:

  • Examine string formatting using the % operator.
  • Learn about the .format() method for string interpolation.
  • Explore Python's f-Strings for string interpolation.

Let's blast off!

Why What's Happening Here?

String formatting and interpolation replace the need for manual string construction, thereby enhancing code readability. Take this example, for instance:

# Concatenating strings
day = 1
message = "Have reached orbit around Mars"
log = "Day " + str(day) + ": " + message + ". All systems are working fine."
print(log)
# Prints: "Day 1: Have reached orbit around Mars. All systems are working fine."

In this case, we're manually constructing the string by combining several parts — it's a bit clunky, isn't it? Let's make this simpler with string formatting and interpolation.

String Formatting

The % operator in Python enables the substitution of parts of a string, simplifying the process:

day = 1
message = "Have reached orbit around Mars"
log = "Day %d: %s. All systems are working fine." % (day, message)
print(log)
# Prints: "Day 1: Have reached orbit around Mars. All systems are working fine."

Here, %d and %s are placeholders for an integer and a string, which are replaced by day and message in the output.

There are several main types you might need to use together with %:

  • %d - number
  • %s - string
  • %f - float
String Interpolation with the .format() Method

The .format() method provides greater control over string interpolation. Let's rewrite the previous log entry:

day = 1
message = "Have reached orbit around Mars"
log = "Day {}: {}. All systems are working fine.".format(day, message)
print(log)
# Prints: "Day 1: Have reached orbit around Mars. All systems are working fine."

With the .format() method, you can use variable names directly in placeholders, which improves readability.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal