我有一段文字如下。
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' 实际上可以出现在单词的任何地方而不是就在最后。
