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

2024-06-16 10:25:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本如下。你知道吗

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)

然而,我想知道是否有任何简单的方法可以做到这一点,可能在一行?你知道吗


Tags: andmostsothatisthisitemimportant
3条回答

您可以使用一行代码将字符串拆分为单词,用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'实际上可以出现在单词的任何地方,而不仅仅是在词尾,那么使用in运算符而不是str.endswith()。你知道吗

下面是另一个可能的(不优雅的)一行:

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"

print(' '.join(map(lambda x : x if '_ABB' in x else x.lower(), 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

注意:这假设您的文本将只按空格分隔单词,因此split()在这里就足够了。如果文本中包含",!."等标点符号,则需要使用regex来拆分单词。你知道吗

扩展的正则表达式方法:

import  re

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"
result = re.sub(r'\b((?!_ABB)\S)+\b', lambda m: m.group().lower(), mytext)

print(result)

输出:

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

详情:

  • \b-词边界
  • (?!_ABB)-lookahead否定断言,确保给定的模式不匹配
  • \S-非空白字符
  • \b((?!_ABB)\S)+\b-整个模式匹配不包含子串的单词_ABB

相关问题 更多 >