find the uppercase letter on a string and replace it

Viewed 113

This is my code :

def cap_space(txt):
    e = txt
    upper = "WLMFSC"
    letters = [each for each in e if each in upper]
    a = ''.join(letters)
    b = a.lower()
    c = txt.replace(a,' '+b)
    return c

who i built to find the uppercase latters on a given string and replace it with space and the lowercase of the latter

example input :

print(cap_space('helloWorld!'))
print(cap_space('iLoveMyFriend'))
print(cap_space('iLikeSwimming'))
print(cap_space('takeCare'))

what should output be like :

hello world!
i love my friend
take care
i like swimming

what i get as output instead is :

hello world!
iLoveMyFriend
iLikeSwimming
take care

the problem here is the condition only applied if there only one upper case latter in the given string for some reasons how i could improve it to get it applied to every upper case latter on the given string ?

4 Answers

Being a regex addict, I can offer the following solution which relies on re.findall with an appropriate regex pattern:

def cap_space(txt):
    parts = re.findall(r'^[a-z]+|[A-Z][a-z]*[^\w\s]?', txt)
    output = ' '.join(parts).lower()
    return output

inp = ['helloWorld!', 'iLoveMyFriend', 'iLikeSwimming', 'akeCare']
output = [cap_space(x) for x in inp]
print(inp)
print(output)

This prints:

['helloWorld!', 'iLoveMyFriend', 'iLikeSwimming', 'akeCare']
['hello world!', 'i love my friend', 'i like swimming', 'ake care']

Here is an explanation of the regex pattern used:

^[a-z]+   match an all lowercase word from the very start of the string
|         OR
[A-Z]     match a leading uppercase letter
[a-z]*    followed by zero or more lowercase letters
[^\w\s]?  followed by an optional "symbol" (defined here as any non word,
                                            non whitespace character)

A simple and crude way. It might not be effective but it is easier to understand

def cap_space(sentence):
    characters = []
    for character in sentence:
        if character.islower():
            characters.append(character)
        else:
            characters.append(f' {character.lower()}')
    return ''.join(characters)

You can make use of nice python3 methods str.translate and str.maketrans:

In [281]: def cap_space(txt):
     ...:     upper = "WLMFSC"
     ...:     letters = [each for each in txt if each in upper]
     ...:     d = {i: ' ' + i.lower() for i in letters}
     ...:     return txt.translate(str.maketrans(d))
     ...: 
     ...: 

In [283]: print(cap_space('helloWorld!'))
     ...: print(cap_space('iLoveMyFriend'))
     ...: print(cap_space('iLikeSwimming'))
     ...: print(cap_space('takeCare'))
hello world!
i love my friend
i like swimming
take care

a is all the matching uppercase letters combined into a single string. When you try to replace them with txt.replace(a, ' '+b), it will only match if all the matchinguppercase letters are consecutive in txt, or there's just a single match. str.replace() matches and replaces the whole seawrch string, not any characters in it.

Combining all the matches into a single string won't work. Just loop through txt, checking each character to see if it matches.

def cap_space(txt):
    result = ''
    upper = "WLMFSC"
    for c in txt:
        if c in upper:
            result += ' ' + c.lower()
        else:
            result += c
    return result
Related