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

佐手、 提交于 2020-08-20 11:50:13

问题


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

Could you please tell me what does f called, so I can google to learn more about it? Thanks guys.

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

回答1:


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.




回答2:


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 there 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.




回答3:


String starting with f are formatted string litrals.

Suppose you have a variable:

pi = 3.14

To catenate it to a string you'd do:

s = "pi = " + str(pi)

Formatted strings come in handy here. Using them you can use this do the same:

s = f"pi = {pi}"

{pi} is simply replaced by the value in the pi



来源:https://stackoverflow.com/questions/58233423/what-does-f-means-before-a-string-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!