无法删除列表的最后一部分

Cannot remove last part of a list

我正在尝试编写程序。该程序读取从文件中获得的字符串,将它们分开,并删除任何“{”并将其替换为冒号(我现在正在尝试这样做)。如果一行中单独有一个 '}',则该行将被完全删除。然后它将新行放入另一个文件。

即如果我有:"Def StackExchange{" 程序应该 return "Def StackExchange:"

我试图通过用空格分割字符串并将其放入列表来解决这个问题。之后我循环遍历字符串并删除任何“{”并在列表中附加“:”。

问题是,当我尝试删除“{”或添加“:”时,出现 ValueError,指出“{”不在列表中,尽管该字符在列表中。

这是我目前拥有的:

        readfile = open(filename + ".bpy","r")
writefile = open(filename + ".py","w")

line = readfile.readline()
string2 = []
while line != "":
    string = line
    string2 = []
    string2.append(string.split())
    if "{" in string2:
        for x in string2:
            try:
                string2.remove("{")
                string2.append(":")
                string = string2.join(" ")
            except:
                pass

    writefile.write(string)
    string2 = []  #This resets string2 and makes it empty so that loop goes on
    line = readfile.readline()


writefile.close()
readfile.close()

编辑:不使用 .replace

问题出在执行 split 方法以将字符串转换为单独的单词。如果其他字符和“{”之间没有 space,它不会分隔“{”。 最好把每个字符分开处理,像下面的代码片段。

string2 = list(string)

它会创造奇迹。 否则,

string2 = []
for character in string:
     string2.append(character)

它会撕开每个字符并将其存储在数组中。现在你的条件将起作用。

对于这项任务,我根本不会在单词列表中使用分割线。我的建议:

with open(filename + '.bpy') as readfile, \
        open(filename + '.py', 'w') as writefile:
    for line in readfile:
        if '{' in line:
            line = line.replace('{', ':')
        elif '}' in line:
            continue

        writefile.write(line)

使用@Aswin 的建议,您可以直接在该循环中替换大括号:

string2 = []
for character in string:
     if character == '{':
          string2.append(':')
     else:
          string2.append(character)
string = ''.join(string2)