0

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 4

5

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()
Sign up to request clarification or add additional context in comments.

Comments

1

you can use list comprehension:

In [1]: strs="18 64 22 5 42 40 48 20 49 33 61 39 62 71"

In [2]: [int(x) for x in strs.split()]
Out[2]: [18, 64, 22, 5, 42, 40, 48, 20, 49, 33, 61, 39, 62, 71]

Comments

0

Try:

map(int, string_numbers.split())

when string_numbers is your space-separated list of numbers.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.