Search code examples
pythonstringlowercase

Convert titlecase words in the string to lowercase words


I want to convert all the titlecase words (words starting with uppercase character and having rest of the characters as lowercase) in the string to the lowercase characters. For example, if my initial string is:

text = " ALL people ARE Great"

I want my resultant string to be:

 "ALL people ARE great"

I tried the following but it did not work

text = text.split()

for i in text:
        if i in [word for word in a if not word.islower() and not word.isupper()]:
            text[i]= text[i].lower()

I also checked related question Check if string is upper, lower, or mixed case in Python.. I want to iterate over my dataframe and for each word that meet this criteria.


Solution

  • You could define your transform function

    def transform(s):
        if len(s) == 1 and s.isupper():
            return s.lower()
        if s[0].isupper() and s[1:].islower():
            return s.lower()
        return s
    
    text = " ALL people ARE Great"
    final_text = " ".join([transform(word) for word in text.split()])