簡體   English   中英

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

[英]What is print(f"...")

我正在閱讀一個 python 腳本,它輸入 XML 個文件並輸出一個 XML 文件。 但是,我不明白打印語法。 有人可以解釋f in print(f"...")的作用嗎?

args = parser.parser_args()

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

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=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2017

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

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

這也將有助於間距,因為它會完全按照字符串寫入

在 Python 3.6 中,引入了 f 字符串(PEP 498)。 簡而言之,它是一種更易讀和快速格式化字符串的方法。

例子:

agent_name = 'James Bond'
kill_count = 9

# old ways
print('{0} has killed {1} enemies '.format(agent_name,kill_count))

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

字符串前面的fF告訴 Python 查看 {} 中的值並用變量值替換它們(如果存在)。 f 格式的最好之處在於您可以在 {} 中做很酷的事情,例如{kill_count * 100}

您可以使用它來調試使用 print eg

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 

還有更多。 閱讀:

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''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 弦

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

你好,我是 Niroshan,25 歲


沒有 f 弦

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

你好,我是 {name} 和 {age} 歲

f function 正在將數據傳輸到您內容中的其他位置。 它主要使用可變數據。

class 方法 (): 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} "

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM