Reputation: 1
from tkinter import *
root =Tk()
text = '["apple", "banana", "orange]"'
data = text.replace("[", "").replace("]", "").replace('"', "")
lst = list(data.split(","))
t = Text(root)
for x in lst:
t.insert(END, x + '\n')
t.pack()
root.mainloop()
But I want it to be like this:
Upvotes: 0
Views: 47
Reputation: 46669
It is because after those replace(...)
, the final result of data
will be:
'apple, banana, orange'
So the result of list(data.split(","))
will be:
['apple', ' banana', ' orange']
To fix it, use list(data.split(", "))
instead for your case.
However you can use json
to parse text
:
from tkinter import *
import json
root =Tk()
#text = '["apple", "banana", "orange]"' # ]" should be "]
text = '["apple", "banana", "orange"]'
lst = json.loads(text)
t = Text(root)
for x in lst:
t.insert(END, x + '\n')
t.pack()
root.mainloop()
Upvotes: 1
Reputation: 764
Try :
from tkinter import *
root =Tk()
text = '["apple", "banana", "orange]"'
data = text.replace("[", "").replace("]", "").replace('"', "")
lst = list(data.split(","))
t = Text(root)
for x in lst:
t.insert(END, x.strip() + '\n')
t.pack()
root.mainloop()
Note:
x.strip()
Upvotes: 0
Reputation: 3121
When you're trying insert x
then after first element it took additional some space. To remove space use strip()
with x
. Follow the code
from tkinter import *
root =Tk()
text = '["apple", "banana", "orange]"'
data = text.replace("[", "").replace("]", "").replace('"', "")
lst = list(data.split(","))
t = Text(root)
for x in lst:
t.insert(END, x.strip() + '\n')
t.pack()
root.mainloop()
Upvotes: 0
Reputation: 6025
You can fix with minimal changes by simply using x.strip()
inside for loop as:
t.insert(END, x.strip() + '\n')
In longer run you might want to fix your lst
as:
lst = [i.strip() for i in data.split(",")]
This way your list does not include trailing or leading spaces and is more useful in longer run and your code as it is works as well.
Upvotes: 0