Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'f' mean before a string in Python? [duplicate]

I wonder what f in print(f'Column names are {"-".join(row)}') does. I tried deleting it and then Column names are {"-".join(row)} become normal string.

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.')
like image 727
KradasA4 Avatar asked Dec 05 '25 19:12

KradasA4


1 Answers

This is called f-strings and are quite straightforward : when using an "f" in front of a string, all the variables inside curly brackets are read and replaced by their value. For example :

age = 18
message = f"You are {age} years old"
print(message)

Will return "You are 18 years old"

This is similar to str.format (https://docs.python.org/3/library/stdtypes.html#str.format) but in a more concise way.

like image 136
Rowin Avatar answered Dec 12 '25 04:12

Rowin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!