What does f
mean before a string in Python? I wonder what the f
in print(f'Column names are {"-".join(row)}')
does. When I tried deleting it, the string Column names are {"-".join(row)}
became a normal string. Can you explain the purpose of f
here?
import csv
with open('CSV_test.txt') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {"-".join(row)}')
line_count += 1
else:
print(f'\t{row[0]} works in the {row[1]} '
f'department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')
I’ve worked with Python for years, and this comes up often! The f
in your string refers to an f-string, introduced in Python 3.6. F-strings let you embed expressions directly into a string using {}
. In your example, "-".join(row)
takes all the elements in the list row
, joins them with a -
as a separator, and places the result inside the string.
For instance, if row = ["1", "2", "3"]
, this line:
print(f'Column names are {"-".join(row)}')
will output:
Column names are 1-2-3
So, in short, the f
makes it possible to include evaluated expressions directly within a string in a clean and readable way. If you remove the f
, the string will lose this dynamic behavior and display the code as plain text. Cool, right? 
Exactly, Richaa! I’ve been exploring Python alternatives to f-strings, so here’s another way to achieve the same result if you’re curious: using the str.format()
method. While f-strings
are newer and more concise, the .format()
method works for embedding dynamic content too. Here’s how you’d do it:
print('Column names are {}'.format('-'.join(row)))
This produces the same result as an f-string:
Column names are 1-2-3
It’s a bit more verbose, but it was the go-to method before Python 3.6. Plus, it still works perfectly if you’re using an older Python version. So, if someone ever asks what does f mean in Python, you can also tell them about these alternatives!
Nice point, Priyanka! While both f-strings and str.format()
are great options, here’s another approach I often use when I want more control or flexibility: list comprehension. This ensures all elements are properly converted to strings (especially helpful with mixed data types):
print('Column names are ' + '-'.join([str(item) for item in row]))
This works the same way by combining each element in row
with a -
, but explicitly converts each element to a string using str(item)
. So if row = [1, 2, 3]
(numbers, not strings), you’d still get:
Column names are 1-2-3
It’s always good to know these alternatives, even though f-strings are my personal favorite for readability. By the way, it’s always fun explaining what does f mean in Python—such a simple feature, yet so powerful!