last year
金市场country asked

Can I use f-strings outside of print()?

Kelish Rai
Expert
last year
Kelish Rai answered

Yes, you can use f-strings outside of print().

An f-string is just a formatted string, meaning you can use it anywhere a string is used.

Example 1: Assigning to a variable:

name = "Alice"

message = f"Hello, {name}"

print(message)  # Output: Hello, Alice

Example 2: Writing to a file:

age = 30

with open("info.txt", "w") as file:
    file.write(f"User age: {age}")

Example 3: Passing as a function argument:

def greet(msg):
    print(msg)

greet(f"Welcome back, {name}!")

In all of these examples, the f-string is being used to build a string dynamically with variables or expressions, then used just like any regular string—stored, written, passed, or returned.

F-strings are one of the most efficient and readable ways to format strings in Python, and you'll keep finding more ways to use them as your projects grow.

Python
This question was asked as part of the Getting started with Python course.