简体   繁体   中英

How can I get this code to include more than just the first occurrence in the loop?

I am trying to take an input and output it with alternating upper and lower case.

Example, if I type in The quick brown fox jumps over the lazy dog the O's in fox and dog aren't output the way i'd like. Same thing happens with double vowels too like "good" or "beets" etc. Is there a way to make the code include occurrences after the first? Also I haven't learned enumerate or any modules like that, I was trying to make it work with what I have learned so far. Thank you.

text = input('Enter a sentence: ')

def sponge(t):
    new = ''
    for i in t:
        if int(t.index(i)) % 2 == 0:
            new += i.lower()
        else:
            new += i.upper()
    return new

print(sponge(text))

Try like this:

text = input('Enter a sentence: ')

def sponge(t):
    new = ''
    for i in range(len(t)):
        if i % 2 == 0:
            new += t[i].lower()
        else:
            new += t[i].upper()
    return new

print(sponge(text))

I guess the problem in your code is that when you use .index to find the index of the character it always returns the first one it finds.

The problem is that the t.index(i) function returns the index of the first occurrence of i . With what you know, just add a counter variable:

text = input('Enter a sentence: ')

def sponge(t):
    new = ''
    counter = 0
    for i in t:
        if counter % 2 == 0:
            new += i.lower()
        else:
            new += i.upper()
        counter += 1
    return new

print(sponge(text))

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