gpt4 book ai didi

python - 在python中将字符串转换为小写的简单方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:14 25 4
gpt4 key购买 nike

我有一段文字如下。

mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN  the lab everyday"

我想将其转换为小写,但其中包含 _ABB 的单词除外。

所以,我的输出应该如下所示。

    mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean  the lab everyday"

我目前的代码如下。

splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)

但是,我想知道是否有任何简单的方法可以在一行中完成此操作?

最佳答案

您可以使用一行将字符串拆分为单词,使用 str.endswith() 检查单词,然后将单词重新组合在一起:

' '.join(w if w.endswith('_ABB') else w.lower() for w in mytext.split())
# 'this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday'

如果 '_ABB' 实际上可以出现在单词的任何地方而不是就在最后。

关于python - 在python中将字符串转换为小写的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com