简体   繁体   English

Python 中的字符串前的“f”是什么意思?

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

I'm new here and also new to Python.我是新来的,也是 Python 的新手。 I wonder what f in print(f'Column names are {"-".join(row)}') does.我想知道f in print(f'Column names are {"-".join(row)}')做了什么。 I tried deleting it and then Column names are {"-".join(row)} become normal string.我尝试删除它,然后Column names are {"-".join(row)}成为普通字符串。

Could you please tell me what f calls, so I can google to learn more about it?你能告诉我f叫什么,所以我可以谷歌了解更多信息吗? 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.')

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.这被称为 f 字符串,非常简单:当在字符串前面使用“f”时,大括号内的所有变量都被读取并替换为那里的值。 For example:例如:

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

Will return "You are 18 years old"将返回“你已经 18 岁”

This is similar to str.format ( https://docs.python.org/3/library/stdtypes.html#str.format ) but in a more concise way.这类似于 str.format ( https://docs.python.org/3/library/stdtypes.html#str.format ),但方式更简洁。

String starting with f are formatted string literals.以 f 开头的字符串是格式化的字符串文字。

Suppose you have a variable:假设你有一个变量:

pi = 3.14

To concatenate 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 {pi}被简单地替换为pi中的值

join method returns a string in which the elements of sequence have been joined by a separator. join方法返回一个字符串,其中序列的元素已通过分隔符连接。 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.然后通过使用 f-string,由{}指定的表达式将被替换为它的值。

Suppose that row = ["1", "2", "3"] then output will be Column names are 1-2-3 .假设row = ["1", "2", "3"]那么 output 将是Column names are 1-2-3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM