2017-02-25 3 views
1

나는 낙타의 경우 문자열을 별도의 단어로 변환하고이를 목록에 추가하는 데 어려움을 겪고 있습니다. 거의 코드를 완성하지만 IndexError : string 인덱스가 범위를 벗어납니다. 누구든지이 도움을 줄 수 있습니까 ?? 출력은 실행이있을 때 :이이 작업을 달성하는 내 방식이다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라고 불리는 카운터를 가지고 있는데, 이는 이전의 '단어'가 끝난 곳을 추적합니다. 그런 다음 전체 문자열 글자를 문자로 반복하고 (대본처럼) 대문자로 이동하면 마지막 단어 변수를 현재 위치로 재설정합니다.

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

나는 당신의 코드 버전을 시험해 보았고 또한 마지막 단어 인 String을 출력하지 않았다. –

+0

다음 줄을 for 루프 뒤에 추가 할 수 있습니다. 'sentence.append (x [lastword :])' –