Search code examples
pythonf-string

What does 'f' mean before a string in Python?


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.')

Solution

  • join method returns a string in which the elements of sequence have been joined by a separator. In your code, it takes row list and join then by separator -.

    Then by using f-string, expression specified by {} will be replaced with it's value.

    Suppose that row = ["1", "2", "3"] then output will be Column names are 1-2-3.