python格式化字符串f_Python 3中的f字符串–格式化的字符串文字

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值