1

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
A.Papa
  • 486
  • 2
  • 8
  • 20

2 Answers2

2

You can use str.istitle() to check whether your word represents the titlecased string, i.e. whether first character of the word is uppercase and rest are lowercase.

For getting your desired result, you need to:

  1. Convert your string to list of words using str.split()
  2. Do the transformation you need using str.istitle() and str.lower() (I am using list comprehension for iterating the list and for generating a new list of words in desired format)
  3. Join back the list to strings using str.join() as:

For example:

>>> text = " ALL people ARE Great"

>>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
'ALL people ARE great'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
2

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()])
Pangeran Bottor
  • 408
  • 3
  • 13