简体   繁体   中英

capitalize every other letter in a string

This is my code:

def mock(s):
    ret = ""
    i = True  
    for char in s:
        if i:
            ret += char.upper()
        else:
            ret += char.lower()
        if char != ' ':
            i = not i
    return ret
print(mock("abcd efgh ijkl"))

output:

AbCd EfGh IjKl

but it has to be like this:

AbCd eFgH IjKl

I don't get what i'm doing wrong and what I should do to fix it.

You could use a simple comprehension and join() :

s = 'abcd efgh ijkl'
morph = ''.join([e.upper() if i%2==0 else e for i, e in enumerate(s)])
print(morph)

Output:

AbCd eFgH IjKl

Note that this does not technically capitalize every other letter (unless you consider spaces to be letters), but instead capitalizes every other index, which it seems is what you want based on your desired output.

To fix your current code, all you would need to do is replace:

if char != ' ':
    i = not i

With:

i = not i
def mock(s):
    ret = ""
    i = True  
    for char in s:
        if i:
            ret += char.upper()
        else:
            ret += char.lower()

        i = not i

    return ret
print(mock("abcd efgh ijkl"))

Outputs:

AbCd eFgH IjKl

The expected output does not care about spaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM