Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping String difficulty python 3

The function of this code is to capitalize letter that appears in the even indexed and lowercase the letter that appears in the odd indexed. Moreover, if whitespace appears between the words, the index has to be reset to 0. As you can see, the first and the second words are executed correctly. Whereas, the third word is incorrect. Instead of C and S being capitalized, 0 and 2 index respectively, A and E are capitalized.

string = 'Weird string case'
result = ''
i=0
for m in string:
    if(i%2==0):
       result = result+m.upper()
       i+=1
    elif(m==' '):
       result = result + m
       i=0
    else:
       result = result + m.lower()
       i+=1
    print(result)

Current Output

 WeIrD StRiNg cAsE

Expected Output

 WeIrD StRiNg CaSe
like image 546
user234568 Avatar asked Aug 08 '26 13:08

user234568


1 Answers

You should test if m is a space first; otherwise if the space occurs when i is even then i would not be reset:

string = 'Weird string case'
result = ''
i=0
for m in string:
    if(m==' '):
       result = result + m
       i=0
    elif(i%2==0):
       result = result+m.upper()
       i+=1
    else:
       result = result + m.lower()
       i+=1
    print(result)
like image 153
blhsing Avatar answered Aug 11 '26 03:08

blhsing



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!