-6

I have problem with compare string with '{' sign. I used incrementation to go forward through string and if function find '{' or '}' should add sign to list. Unfortunately, the output is "IndexError: string index out of range". Do you have ideas how to do this?

while i <= len(summary):
    if summary[i] == '{':
        nws_otw.append(summary[i])
    if summary[i] == '}':
        nws_zam.append(summary[i])
    i+=1
  • You should iterate over the string using a `for ... in ...` loop. The reason you’re getting the error is because the last index in a list or string is the length minus 1. – AMC Dec 13 '19 at 22:12
  • 4
    You should use `i < len(summary)` instead `i <= len(summary)` – Stepan Dec 13 '19 at 22:13

3 Answers3

1

The last index of a string or list is len() - 1. You should probably use a for ... in ... loop anyway. In fact, you can get rid of the loop entirely by checking if a substring is in a string using sub in my_string.

AMC
  • 2,642
  • 7
  • 13
  • 35
0

Since the strings start with index 0, it is incorrect to iterate through the string using while i <= len(summary):, you should use while i < len(summary): instead.

Better yet is to use something like:

for i in range(len(summary)):
Ivan86
  • 5,695
  • 2
  • 14
  • 30
0

I see that you didn't say what 'i' should start at either. It needs to be initialized before being used in the while loop. I posted some example code here, that works.

summary = "{This is some text}"
nws_otw = []
nws_zam = []
i = 0  # Needs to be present
while i < len(summary):
    if summary[i] == "{":
        nws_otw.append(summary[i])
    if summary[i] == "}":
        nws_zam.append(summary[i])
    i += 1
Rahul P
  • 2,493
  • 2
  • 17
  • 31