前言
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。
PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取
f-String 表示法介绍
格式化字符串是编程的一个基本且必不可少的部分。F-string (在 Python3.6中引入)提高了格式化丰富字符串的简单性和直观性。
f-String 方法(格式化的字符串)要求在字符串的开头有一个 f (例如:f"hello")。有许多高级方法可用于格式化漂亮的字符串,下面将讨论5个这样的方法。
1. 字符串中的变量
在适当位置插入/替换变量。
name = "Alexander Hamilton"
print(f"hello {name}")
# hello Alexander Hamilton
2. 字符串中的变量格式化
设置变量(如整数)的格式。
2.1 打印一个带逗号的大整数:
x = 2*10**5
print(f"You have ${x:,} in your bank account")
# You have $200,000 in your bank account
2.2 打印一个具有指定数字的浮点数:
pi = 3.1415926535897932384
print(f"The first 5 digits of pi are {pi:.5f}")
# The first 5 digits of pi are 3.14159
3. In-Place 布尔逻辑:
也许您希望根据几个条件格式化字符串。f-string 方法允许在适当的位置上使用布尔参数,正如您希望从 lambda 表示法得到的那样。
new_user = False
user_name = "Alexander Hamilton"
print(f"{'Congrats on making your account' if new_user else 'Welcome back'} {user_name}!")
# Welcome back Alexander Hamilton!
4. 打印变量名和值
在 python 3.8中,f-string 表示法允许打印变量名和它们的值,这是一个特别有用的调试工具:
max_price = 20000
min_price = 4000
print(f"{max_price=:,} | {min_price=:,})
# max_price=20,000 | min_price=4,000
5. 在预填充字符串中格式化变量
字符串格式化允许替换预填充字符串中的变量。
这对于允许外部用户格式化程序将要填写的电子邮件信息特别有用。
5.1 Str.Format 方法(首选)
my_message = "Welcome to our platform {FNAME}! Your favorite ice cream flavor is {FLAVOR}."
FNAME = "Alexander"
FLAVOR = "Mint Chocolate Chip"
my_message_formatted = my_message.format(**{"FNAME":FNAME, "FLAVOR":FLAVOR})
print(my_message_formatted)
# Welcome to our platform Alexander! Your favorite ice cream flavor is Mint Chocolate Chip.
5.2 f-string 方法(带 Eval)
这里有一个 f -string 方法“不太合适”的实例(仅仅是因为它打算在代码中使用...)
my_message = "Welcome to our platform {FNAME}! Your favorite ice cream flavor is {FLAVOR}."
FNAME = "Alexander"
FLAVOR = "Mint Chocolate Chip"
my_message_formatted = eval(f”f’{my_message}’”)
print(my_message_formatted)
# Welcome to our platform Alexander! Your favorite ice cream flavor is Mint Chocolate Chip.
总结
F-string 字符串表示法是一种格式化字符串的简便方法。上面演示了5个 python 3.8中格式化字符串的高级方法。
可以考虑在自己的 python 代码中实现这些方法。