Skip to content Skip to sidebar Skip to footer

Removing Capital Letters From A Python String

I am trying to figure out how to remove capital letters from a string using Python but without the for loop. I’m trying to do this while traversing a list using a while loop. S

Solution 1:

Strings are immutable, so you can’t literally remove characters from them, but you can create a new string that skips over those characters.

The simplest way is:

s = ''.join(ch for ch in s if not ch.isupper())

If you want to do this without for for some reason (like an assignment requirement), we can write this out as an explicit loop, and then convert it to a while. So:

result = []
for ch in s:
    if not ch.isupper(): result.append(ch)
s = ''.join(result)

To change the loop, we have to manually setup and next the iterator, but it may be easier to understand with just a plain int as an index instead of an iterator:

result = []
i = 0
while i < len(s):
    ch = s[i]
    if not ch.isupper(): result.append(ch)
    i += 1
s = ''.join(result)

Of course this is more verbose, slightly less efficient, and easier to get wrong, but otherwise it’s basically equivalent, and it meets your strange requirements.

In real life, there might be better ways to do this—e.g., str.translate with a map from all caps to None should be pretty fast if you only care about ASCII caps—but I assume your teacher doesn’t want you thinking in those directions, they want you thinking about the loops explicitly. (Of course there is a loop in str.translate, or re.sub, etc., that loop is just hidden under the covers where you don’t see it.)

If you need to do this to multiple strings in a list, you’d wrap it up in a function, and apply it to each string in the list, using a comprehension—or you can write it out as a loop statement, and convert it to a while loop, if you prefer, in exactly the same way. For example:

def remove_caps(s):
    result = []
    i = 0
    while i < len(s):
        ch = s[i]
        if not ch.isupper(): result.append(ch)
        i += 1
    return ''.join(result)

strings = ['aBC', 'Abc', 'abc', '']
new_strings = []
i = 0
while i < len(strings):
    new_strings.append(remove_caps(strings[i]))
    i += 1

Solution 2:

You have a few options here:

1) If you simply want to convert all upper-case letters to lower-case, then .lower() is the simplest approach.

s = 'ThiS iS A PyTHon StrinG witH SomE CAPitaL LettErs'

Gives:

this is a python string with some capital letters

2) If you want to completely remove them, then re.sub() is a simple approach.

import re

print(re.sub(r'[A-Z]', '', s))

Gives:

hi i  yon trin wit om ita ettrs

3)

For a list of strings, you could use a list comprehension:

#Option1
[i.lower() for i in s])

#Option2
import re

[re.sub(r'[A-Z]', '', i) for i in s])

#Option3 (as mentioned by @JohnColeman)
[''.join([j for j in i if not j.isupper()]) for i in s]

Post a Comment for "Removing Capital Letters From A Python String"