2017-02-25 114 views
1

我很难将驼峰字符串转换为单独的单词并将它们附加到列表中。它几乎完成了代码,但它提供了一个IndexError:字符串索引超出范围。 请任何人都可以帮忙吗? 输出运行时为:indexerror for循环问题

['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 
+0

它打印整个字符串,但不是最后的“字符串”从实际字符串 –

+0

这就像一个医生试图通过在纸张上的孔寻求诊断的疾病。 –

+0

我建议在您的文章中添加修改,并使用与图片相对的代码进行更新。 – GedAWizardofEarthSea

回答

0

这是我完成这个任务的方式。我有一个名为lastword的柜台,它跟踪上一个'单词'结束的位置。然后我通过字母逐字地循环整个字符串(就像你一样),如果我得到一个大写字母,那么你将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 
+0

谢谢阿比德。感谢帮助。有没有什么机会可以帮我解决我的代码问题,因为我需要在这个例子中使用特定的版本。 –

+0

我试过你的版本的代码,它也没有打印最后一个字是字符串。 –

+0

您可以在for循环后添加这一行: 'sentence.append(x [lastword:])' –