I have some numbers that I want to input in tkinter : 18 64 22 5 42 40 48 20 49 33 61 39 62 71. And I want them look like [18,64,22,5,42,40....]
4 Answers
Use text.split() to make a list of strings. The split method will by default split on whitespace. If you want a list of ints, you could use map(int, text.split()):
In [6]: text = '18 64 22 5 42 40 48 20 49 33 61 39 62 71'
In [7]: text.split()
Out[7]: ['18', '64', '22', '5', '42', '40', '48', '20', '49', '33', '61', '39', '62', '71']
In [8]: map(int, text.split())
Out[8]: [18, 64, 22, 5, 42, 40, 48, 20, 49, 33, 61, 39, 62, 71]
And to show how it can be used with Tkinter:
import Tkinter as tk
class App(object):
def read_entry(self, event):
entry = event.widget
text = entry.get()
print(map(int, text.split()))
def __init__(self):
entry = tk.Entry()
entry.bind('<Return>', self.read_entry)
entry.pack()
entry.focus()
root = tk.Tk()
app = App()
root.mainloop()
Comments
function that outputs exactly [18,64,22,5,42,40....]
def format_nrs(nr_str, n=6):
nrs = nr_str.split()
s = ",".join(nrs[:n])
if n >= len(nrs):
return "[%s]" % s
else:
return "[%s...]" %s
usage :
n_str = "18 64 22 5 42 40 48 20 49 33 61 39 62 71"
print format_nrs(n_str)
print format_nrs(n_str, 10)
print format_nrs(n_str, 14)
output:
[18,64,22,5,42,40...]
[18,64,22,5,42,40,48,20,49,33...]
[18,64,22,5,42,40,48,20,49,33,61,39,62,71]