从txt文件读取后,如何从字符串中删除{和}字符?

2024-10-03 02:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序应该读取一个.txt文件并在窗口中打印内容,但是输出中有这些奇怪的'{'和'}'字符。txt文件包含一个或多个单词,在单独的一行中。你知道吗

我试过替换字符,但最后只换了一行,我不想要。你知道吗

这是我目前掌握的代码:

if name == "<name>":
            file = open("<name>.txt", "r")
            wishlist = file.readlines()
            listtext.setText(wishlist) 

运行时,窗口中的输出如下(例如):

{Television
 }{Alarm Clock
}{Lamp
    }

当我希望它不带'{'和'}'的时候

提前谢谢!你知道吗


Tags: 文件代码name程序txt内容ifopen
3条回答

我想这个小剪辑就是你需要的

if name == "<name>":
    file = open("<name>.txt", "r")
    wishlist = file.readlines()

    wishlist=[i.replace('{','') for i in wishlist] # removes all {s from all indices
    wishlist=[i.replace('}','') for i in wishlist] # removes all }s from all indices

    listtext.setText(wishlist) 

你可以用字符串.替换(char,“”)函数在一个简单的循环中删除不需要的字符,并且不影响输出的其余部分。你知道吗

s='''{Television
 }{Alarm Clock
}{Lamp
    }'''
remove='{}'
for char in remove:
        s = s.replace(char, " ")

print(s)

output:

Television
   Alarm Clock         
Lamp                                                      

原因是您使用了readlines()方法,该方法返回文件中的行列表。因此,listtext中可能有某种方法将{和}附加到列表的每个元素

相关问题 更多 >