Reputation:
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.
Upvotes: 1
Views: 5011
Reputation: 51175
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
Upvotes: 3
Reputation: 493
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
Upvotes: 1