我正在阅读一个Python脚本,它接受XML文件作为输入并输出XML文件。然而,我不理解打印语法。有人可以解释一下在print(f"...")
中的f
是什么意思吗?
args = parser.parser_args()
print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")
我正在阅读一个Python脚本,它接受XML文件作为输入并输出XML文件。然而,我不理解打印语法。有人可以解释一下在print(f"...")
中的f
是什么意思吗?
args = parser.parser_args()
print(f"Input directory: {args.input_directory}")
print(f"Output directory: {args.output_directory}")
f
在 Python 3.6 中是新的,它代表着格式化字符串字面值。
>>> 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
repr()函数返回给定对象的可打印表示字符串。
- Prashant Zombadestr(name)
和repr(name)
有什么区别? - Ricardo Barros Lourençoagent_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')
f
或F
告诉Python查看{}中的值、表达式或实例,并将它们替换为变量值或结果(如果存在)。f格式化最好的事情是你可以在{}中做很酷的事情,例如:{kill_count * 100}
。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
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__
允许您与此功能进行交互。示例
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
还有更多。阅读:
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
这也将有助于间距,因为它将完全按照字符串编写。
word_string
缺少闭合引号。 - Pedro Lobito以'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)}
在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}岁。
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)
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} "