Home > database >  How to fix IndexError: String index out of range - Python
How to fix IndexError: String index out of range - Python

Time:12-28

I am trying to make a parser for my text adventure. I used a text file called test.txt. I keep getting IndexError: string index out of range. How can I fix this?

parser.py

def parse(file):
  data = {}
  
  with open(file, "r") as f:
    lines = f.readlines()
    f.close()

  for line in lines:
    line = line.strip()
    
    if line[0] == "@":
      name = line[1:]
      name = name.replace("\n", "")

      data[name] = {}

    if line[0] == "-":
      prop = line.split(":")
      prop_name = prop[0].replace("-", "")
      prop_name = prop_name.replace("\n", "")
      
      prop_desc = prop[1][1:]
      prop_desc = prop_desc.replace("\n", "")

      data[name][prop_name] = prop_desc

    

  return data
      
    
print(parse("test.txt"))

test.txt

@hello

  -desc: Hello World! Lorem ipsum
  -north: world

@world

  -desc: World Hello! blah
  -south: hello
  

CodePudding user response:

You're stripping the newlines (line = line.strip()), so if a line is empty, there is just an empty string and line[0] is out of range.

You should test if the line is truthy:

if line and line[0] == "-":

Or, better, in the beginning of the loop, skip blank lines:

for line in lines:
    if line == '\n':
        continue
    # rest of code

CodePudding user response:

Since there is many "\n" in your text, you should ignore them in file reading. try this:

  with open(file, "r") as f:
    lines = f.readline().splitlines()
    f.close()
  • Related