What You'll Learn

Ready to explore combining text with variables in Python using f-strings? This powerful feature makes it effortless to create dynamic and readable strings by embedding variables directly within them.

Code Example

For a trip planning scenario, consider these variables:

# Travel variables
destination = "Paris"
number_of_days = 5
trip_cost = 1200.50 # Notice how we can store numbers in variables that are not integers!

Using f-strings enables you to neatly include variable values in your text output:

# Using f-strings for travel details
print(f"I am planning a trip to {destination}.")
print(f"The trip will be for {number_of_days} days.")
print(f"The estimated cost of the trip is ${trip_cost}.")

output:

I am planning a trip to Paris.
The trip will be for 5 days.
The estimated cost of the trip is $1200.5.

f-strings allow for inline variable insertion, which means you can directly insert the value of a variable into a string by prefacing the string with f and enclosing variable names in curly braces {}.

Note on constants: You may sometimes see variable names written in all capital letters, such as DESTINATION. In Python, this is a convention that tells other programmers, "this value should not change." Python does not enforce constants, so the value can still be reassigned, but the uppercase name is a helpful signal.

Why It Matters

F-strings offer a concise and readable way to incorporate variables into strings, enhancing code clarity. They're especially useful for outputting data in a more engaging and informative manner. Through practice, you'll get comfortable with this skill, which is crucial for effective Python programming.

Let's dive into the practice exercises!

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