循环issu的索引器

2024-05-14 13:59:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难将一个驼峰大小写字符串转换成单独的单词,并将它们添加到列表中。它几乎完成了代码,但它给出了一个索引器:字符串索引超出范围。 有谁能帮忙吗?? 运行时的输出为:

['This']
['This', 'Is']
['This', 'Is', 'A']
['This', 'Is', 'A', 'Camel']
['This', 'Is', 'A', 'Camel', 'Case']
Traceback (most recent call last):
for i in string[char]:
IndexError: string index out of range

Picture of code

List = []
string = "ThisIsACamelCaseString"
newstring = ""
count = 0
char = 0
null = 0

for i in string[char:]:
    if i == i.upper():
        newstring = newstring + i
        count += 1
        char += 1
    for i in string[char]:      **< error here**
        if i == i.upper() and char == 1:
            null += 1
        elif i == i.lower():
            newstring = newstring + i
            char += 1
            count += 1      
        elif i == i.upper() and count > 0:
            List.append(newstring)
            print(List)
            newstring = ""
            break

Tags: of字符串inforstringifiscount
1条回答
网友
1楼 · 发布于 2024-05-14 13:59:39

这是我完成这项任务的方法。我有一个名为lastword的计数器,它跟踪上一个“word”的结束位置。然后我一个字母一个字母地循环遍历整个字符串(就像您所做的那样),如果得到一个大写字母,那么您可以将lastword变量重置为当前位置

x = "ThisIsACamelCaseString"

#list to store results
sentence = []            
lastword = 0
#count keeps track of what position we are at
for count, letter in enumerate(x):
    #I use the isupper() methd to see if letter is uppercase
    if letter.isupper():
        word = x[lastword:count]
        lastword = count
        #if word is needed because otherwise the first 'word' will be literally nothing
        if word:
            sentence.append(word)
print sentence

相关问题 更多 >

    热门问题