【发布时间】:2022-10-25 00:12:27
【问题描述】:
我正在努力使我的文本像问题一样在大写和小写之间交替出现。它似乎在索引中跳过了 3,我不知道为什么。
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
【问题讨论】:
-
请将您的代码作为文本发布。
-
将代码视为图像使得复制粘贴和测试变得更加困难
-
index是非常不适合这项工作的工具。请记住,index返回字符的第一次出现。如果您有 3 个 L,则每次都会返回相同的 L。你需要让你的循环通过索引。 -
考虑使用列表比较像这样 -
ans = [ch.upper() if not idx%2 else ch.lower() for idx, ch in enumerate(word)]