python - 循环字符串难度python 3

标签 python string loops

这段代码的作用是将出现在偶数索引中的字母大写,将出现在奇数索引中的字母小写。此外,如果单词之间出现空格,则必须将索引重置为 0。如您所见,第一个和第二个单词被正确执行。然而,第三个词不正确。 C和S不大写,0和2索引分别大写A和E。

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)

当前输出

 WeIrD StRiNg cAsE

预期输出

 WeIrD StRiNg CaSe

最佳答案

你应该先测试m是否是一个空格;否则,如果当 i 为偶数时出现空格,则 i 不会被重置:

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)

关于python - 循环字符串难度python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52657106/

相关文章:

python - 将小部件关联到组中,用于隐藏和显示,wxpython

python - 在 openpyxl 中关闭文件

javascript - 给一串html添加粗体标签

javascript - 从 Google 表格循环

java - 用 Java 8 平面图替换嵌套循环

python - 如何正确地将 scipy.sparse CSR 矩阵传递给 cython 函数?

python - 在numpy中乘以对数概率矩阵的数值稳定方法

c# - 我怎样才能删除最后一部分?

c++ - boost::filesystem::path::string() 输出的奇怪行为

r - 在多个列上嵌套 if else 语句