user8871463
user8871463

Reputation:

Easy way of converting a string to lowercase in python

I have a text as follows.

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"

I want to convert it to lowercase, except the words that has _ABB in it.

So, my output should look as follows.

    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"

My current code is as follows.

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

However, I want to know if there is any easy way of doing this, possibly in one line?

Upvotes: 1

Views: 173

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

Here is another possible(not elegant) one-liner:

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())))

Which Outputs:

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

Note: This assumes that your text will only seperate the words by spaces, so split() suffices here. If your text includes punctuation such as",!.", you will need to use regex instead to split up the words.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Extended regex approach:

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)

The output:

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

Details:

  • \b - word boundary
  • (?!_ABB) - lookahead negative assertion, ensures that the given pattern will not match
  • \S - non-whitespace character
  • \b((?!_ABB)\S)+\b - the whole pattern matches a word NOT containing substring _ABB

Upvotes: 3

Chris_Rands
Chris_Rands

Reputation: 41158

You can use a one liner splitting the string into words, check the words with str.endswith() and then join the words back together:

' '.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'

Of course use the in operator rather than str.endswith() if '_ABB' can actually occur anywhere in the word and not just at the end.

Upvotes: 11

Related Questions