金
金市场
asked

Expert
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, AliceExample 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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer