繁体   English   中英

我怎样才能让这段代码不仅仅包含循环中的第一次出现?

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

我正在尝试获取输入并交替使用大写和小写输出。

例如,如果我输入The quick brown fox jumps over the lazy dog ,则 fox 和 dog 中的 O 不会按照我想要的方式输出。 同样的事情也发生在双元音上,比如“good”或“beets”等。有没有办法让代码在第一个之后出现? 此外,我还没有学习枚举或任何类似的模块,我试图让它与我到目前为止所学的一起工作。 谢谢你。

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))

试试这样:

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))

我猜你的代码中的问题是,当你使用.index查找字符的索引时,它总是返回它找到的第一个。

问题是t.index(i)函数返回i第一次出现的索引。 据您所知,只需添加一个计数器变量:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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