Python 中的 5 个高级字符串方法

欢迎关注 “小白玩转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 代码中实现这些方法。

如果您有其他值得注意的字符串方法,可以后台分享给我们~

·  END  ·

HAPPY LIFE

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值