【发布时间】:2018-07-21 21:05:30
【问题描述】:
我正在尝试编写一个程序。该程序读取从文件中获得的字符串,将它们分开,并删除任何“{”并用冒号替换它(我现在正在尝试这样做)。如果一行本身有一个“}”,则该行将被完全删除。然后它将新行放入另一个文件中。
即如果我有:“Def StackExchange{” 该程序应返回“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
【问题讨论】:
-
你为什么不用
.replace("{",":")? -
您正在从正在循环的同一个列表中删除元素,这是错误的
标签: python string list file-handling