python格式化字符串f
In Python 3.6, a new feature for string formatting is introduced that is "Literal String Interpolation" also knows as "f-strings formatting".
在Python 3.6中,引入了用于字符串格式化的新功能,即“文字字符串插值”,也称为“ f字符串格式” 。
Formatting strings are very easy by f-strings, we have to prefix the literal f before the string to be printed. That's why it is called f-strings formatting. To print the values of the objects (variables) – pass the variable name within the curly braces {}.
通过f-strings格式化字符串非常容易,我们必须在要打印的字符串之前为文字f加上前缀。 这就是为什么将其称为f字符串格式。 要打印对象(变量)的值,请在大括号{}中传递变量名称。
Syntax:
句法:
print(f"{variables}")
or
print(f'{variables}')
Example 1:
范例1:
# Python program to demonstrate the
# example of f-strings formatting
a = 10
b = 123.45
c = 'X'
d = "Hello"
# printing one by one
print("Printing one by one...")
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print(f"d = {d}")
print() # prints new line
# printing together
print("Printing together...")
print(f"a = {a}, b = {b}, c = {c}, d = {d}")
Output:
输出:
Printing one by one...
a = 10
b = 123.45
c = X
d = Hello
Printing together...
a = 10, b = 123.45, c = X, d = Hello
Example 2:
范例2:
# Python program to demonstrate the
# example of f-strings formatting
name = "Mike"
age = 21
country = 'USA'
# printing one by one
print("Printing one bye one...")
print(f"Name : {name}")
print(f"Age : {age}")
print(f"Country : {country}")
print() # prints new line
# printing without messages
print("Printing without messages...")
print(f"{name} {age} {country}")
print()
# printing together
print("Printing together...")
print(f"Name: {name}, Age: {age}, Country: {country}")
Output:
输出:
Printing one bye one...
Name : Mike
Age : 21
Country : USA
Printing without messages...
Mike 21 USA
Printing together...
Name: Mike, Age: 21, Country: USA
Example 3:
范例3:
# Printing table using f-strings
a = 10
# printing the table
print(f"Table of {a}:")
for i in range(1, 11):
print(f"{a} x {i} = {a*i}")
Output:
输出:
Table of 10:
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
翻译自: https://www.includehelp.com/python/f-strings-in-python-3-formatted-string-literals.aspx
python格式化字符串f