什么是 print(f"...")?

133

我正在阅读一个Python脚本,它接受XML文件作为输入并输出XML文件。然而,我不理解打印语法。有人可以解释一下在print(f"...")中的f是什么意思吗?

args = parser.parser_args()

print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")

2
f-strings。这种语法只在Python 3.6及以上版本中可用。 - Abdul Niyas P M
3
它们是 f-string。这是从 Python 3.6 引入的新概念。 https://realpython.com/python-f-strings/ - ranka47
7个回答

131
f 在 Python 3.6 中是新的,它代表着格式化字符串字面值
格式化字符串字面值或f-string是以f或F为前缀的字符串字面值。这些字符串可以包含由花括号{}括起来的替换字段,这些字段是表达式。而其他字符串字面值始终具有常量值,格式化字符串实际上是在运行时评估的表达式。
一些格式化字符串字面值的示例:
>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."

>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35

>>> today = datetime(year=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023

>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400

11
对于初学Python的人来说:repr()函数返回给定对象的可打印表示字符串。 - Prashant Zombade
1
@PrashantZombade 在这种情况下,str(name)repr(name)有什么区别? - Ricardo Barros Lourenço
1
@RicardoBarrosLourenço https://dev59.com/KHM_5IYBdhLWcg3wTRPLstr()和repr()的区别是什么? - Joe Mornin

50
在Python 3.6中,引入了f-string,即格式化字符串字面量(PEP 498)。简而言之,它是一种更易读且更快速的字符串格式化方式。
示例:
agent_name = 'James Bond'
kill_count = 9


# old ways
print("%s has killed %d enemies" % (agent_name,kill_count))

print('{} has killed {} enemies'.format(agent_name,kill_count))
print('{name} has killed {kill} enemies'.format(name=agent_name,kill=kill_count))
    

# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')

在字符串前面的fF告诉Python查看{}中的值、表达式或实例,并将它们替换为变量值或结果(如果存在)。f格式化最好的事情是你可以在{}中做很酷的事情,例如:{kill_count * 100}
你可以使用它来使用print进行调试。
print(f'the {agent_name=}.')
# the agent_name='James Bond'

格式化,例如零填充、浮点数和百分比舍入更加容易:

print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with  0.82 or  81.8% accuracy 

更酷的是嵌套和格式化的能力。示例日期{{date}}。

from datetime import datetime

lookup = {
    '01': 'st',
    '21': 'st',
    '31': 'st',
    '02': 'nd',
    '22': 'nd',
    '03': 'rd',
    '23': 'rd'
}

print(f"{datetime.now(): %B %d{lookup.get('%B', 'th')} %Y}")

# April 14th 2022

漂亮的格式化也更容易

tax = 1234

print(f'{tax:,}') # separate 1k \w comma
# 1,234

print(f'{tax:,.2f}') # all two decimals 
# 1,234.00

print(f'{tax:~>8}') # pad left with ~ to fill eight characters or < other direction
# ~~~~1234

print(f'{tax:~^20}') # centre and pad
# ~~~~~~~~1234~~~~~~~~
< p > __format__ 允许您与此功能进行交互。示例


{{__format__}}允许您定制此功能。示例:

class Money:
    
    def __init__(self, currency='€'):
        self.currency = currency
        
    def __format__(self, value):
        
        return f"{self.currency} {float(value):.2f}"
        
        
tax = 12.34
money = Money(currency='$')
print(f'{money: {tax}}')
# $ 12.34

还有更多。阅读:


“更易读”……说真的,“……”.format() 有什么问题吗?使用 print(f'....' {}) 看起来越来越不像 Python 风格了。我喜欢代码的进步,但这只是为了添加东西而添加东西。 - ThePhi
我希望我的回答并不意味着“{}...”.format出了什么问题。就像" ".join(...)一样,我认为类似于format("...{}", ...)和类似的join(..., " ")会更易读。这并没有错,只是可读性因人而异。☺️ - Prayson W. Daniel

18

f字符串也被称为字面字符串,它可以插入一个变量到字符串中并将其作为一部分,这样就不需要再像以前那样

x = 12
y = 10

word_string = x + ' plus ' + y + 'equals: ' + (x+y)

相反,您可以这样做

x = 12
y = 10

word_string = f'{x} plus {y} equals: {x+y}'
output: 12 plus 10 equals: 22

这也将有助于间距,因为它将完全按照字符串编写。


1
第二个 word_string 缺少闭合引号。 - Pedro Lobito

4

'f''F'前缀字符串,并在其中使用表达式{expression}是一种格式化字符串的方式,可以在字符串中包含Python表达式的值。

以以下代码为例:

def area(length, width):
    return length * width

l = 4
w = 5

print("length =", l, "width =", w, "area =", area(l, w))  # normal way
print(f"length = {l} width = {w} area = {area(l,w)}")     # Same output as above
print("length = {l} width = {w} area = {area(l,w)}")      # without f prefixed

输出:

length = 4 width = 5 area = 20
length = 4 width = 5 area = 20
length = {l} width = {w} area = {area(l,w)}

2

在Python中,f-string允许您使用字符串模板格式化数据以进行打印。
以下示例将帮助您澄清

使用f-string

name = 'Niroshan'
age  = 25;
print(f"Hello I'm {name} and {age} years young")

你好,我叫Niroshan,今年25岁。


没有f-string的情况下

name = 'Niroshan'
age  = 25;
print("Hello I'm {name} and {age} years young")

你好,我叫{name},今年{age}岁。


2
args = parser.parser_args()

print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")

是相同的意思

print("Input directory: {}".format(args.input_directory))
print("Output directory: {}".format(args.output_directory))

它也与之相同

print("Input directory: "+args.input_directory)
print("Output directory: "+args.output_directory)

请注意,严格来说,这三种技术并不等价。它们各自具有不同的性能特征,并且在处理非字符串参数方面也有所不同。 - Brian61354270

0

f函数是在您的内容中将数据传输到其他地方。它主要用于可变数据。

类方法(Methods): def init(self, F, L, E, S, T): self.FirstName = F self.LastName = L self.Email = E self.Salary = S self.Time = T

    def  Salary_Msg(self):
        #f is called function f
        #next use {write in}
        return f{self.firstname} {self.Lastname} earns AUD {self.Salary}per {self.Time} "

您可以通过提供额外的支持信息来改善您的回答。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的回答是否正确。您可以在帮助中心中找到有关如何撰写良好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接