Python массивное разделение текста

Вот сразу код:

import re

class Interpreter:
    def __init__(self, filename):
        self.file_name = filename
        self.variables = {}
        with open(filename) as code:
            self.lines = len(code.readlines())
        self.current_line = 1

    def split_code(self, input_str):
        pattern = r'\w+|\.|\=|<.*?>|\"w+"'
        result = re.findall(pattern, input_str)
        for i in range(len(result)):
            try:
                result[i] = int(result[i])
            except ValueError:
                pass
        return result

    def lex(self, c):
        if c[0] == "out":
            text = ""
            for n in range(len(c)-1):
                t = c[n]
                if t[0:2] == "__":
                    try:
                        text += self.variables[t[2:]]
                    except KeyError:
                        print(f"Ошибка. Перменная {t[2:]} отсутствует!")
                else:
                    text += t
                n += 1
                text += " "
            print(text)



        elif c[1] == "=":
            if c[2] == "inp":
                vvod = input(" ".join(c[3:]) + "\n")
                self.variables[c[0]] = vvod
            else:
                zn = c[2:]
                self.variables[c[0]] = zn



            
    def run(self):
        with open(self.file_name, "r", encoding="utf-8") as code:
            while self.current_line <= self.lines:
                line = code.readline().replace("\n", "")
                codeline = self.split_code(line)
                self.lex(codeline)
                self.current_line += 1




inter = Interpreter("programm.txt")
inter.run()

Код самой программы которую он воспроизводит:

x = 123абв
out Слово1 слово2 __x перменная не нойдынээуэ

Когда запускаю, выводит такую ошибку:

text += self.variables[t[2:]]
TypeError: can only concatenate str (not "list") to str

Но t у меня является текстом, который я могу как бы разделить квадратными скобками. Подскажите, в чем проблема?


Ответы (1 шт):

Автор решения: Maksim Alekseev

Не знаю какой результат ты ожидаешь, но в self.variables[t[2:]] у тебя находится список и ты патаешься к строке прибавить его, ошибка об этом и говорит, нельзя складывать строки и списки.

Можно исправить на:

text += ''.join(self.variables[t[2:]])
→ Ссылка