Ata0608
Ata0608

Reputation: 1

Text won't line up

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()

The output is like this: enter image description here

But I want it to be like this: enter image description here

Upvotes: 0

Views: 47

Answers (4)

acw1668
acw1668

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

Yash Makan
Yash Makan

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

mhhabib
mhhabib

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

Hamza
Hamza

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

Related Questions