Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing capital letters from a python string [closed]

Tags:

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.

So how can I remove the capital letters in a provided string?

like image 479
Wise students Avatar asked Mar 13 '26 16:03

Wise students


1 Answers

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
like image 87
abarnert Avatar answered Mar 15 '26 07:03

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!