简体   繁体   中英

Trying to figure out why some of the output isn't working

complete beginner here. I am trying to get each letter in a sentence to alternate between uppercase and lowercase. I was wondering why in the output of my code does the whole 'fox' and 'dog' stay all in lower case? I figured 1 or 2 but im lost at why all 3 in both words.

text = input('Enter a sentence: ')

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

print(sponge(text))

when I enter 'the quick brown fox jumps over the lazy dog' it does that. Also when I type something with 2 E's or 2 O's both will be capitalized even if they're next to each other.

Also I know there are easier ways to do this but I am not that far in learning yet so I am trying to do it with what I currently know as opposed to modules and all that. Thank you for your time.

Don't use t.index(i) . That returns the position of the first occurrence of i in the string. If you have duplicate letters, you'll use the position of the first one when deciding what to do with all the repetitions.

Use enumerate() to get both the letter and its index at the same time.

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

Without enumerate you can use range(len(t)) and then access t[index] .

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

Or you can use a separate variable to keep track of whether it's an even or odd index.

def sponge(t):
    new = ''
    even = True
    for letter in t:
        if even:
            new += letter.lower()
        else:
            new += letter.upper()
        even = not even

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