[Tutor] how to use int and split() simultaneously

Dario Lopez-Kästen cl2dlope at gmail.com
Thu Dec 8 14:43:41 CET 2011


oh, yes,  no top posting. See below.

On Thu, Dec 8, 2011 at 1:33 PM, surya k <suryak at live.com> wrote:

>
> This is something I am trying to do..
> Say, we are entering a string "1 2 3 4 5".so, I want to assign the numbers
> directly as numbers. how can I do it?
> I could put that numbers as string but not as number..
> strNum = raw_input('enter:').split()
> I can convert the list into numbers by doing this...
> for i in range(len(strNum)):   strNum[i] = int(strNum[i]).
> but I feel, its a long process. How can I do it in the shortest possible
> way??
>

Using a list comprehension is one example of a compact way of doing it:

strNum = raw_input("enter numbers, separated by space: ").split()
strNum = [int(x) for x in strNum]

You would have to assume that the entire string consists of tokens that can
be type cast into integers. If not you get an error:

>>> strNum = raw_input("enter numbers, separated by space: ").split()
enter numbers, separated by space: 1 2 3 4 5 66 asd
>>> strNum = [int(x) for x in strNum]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): asd

In that case a for loop with a try-except would better:

strNum = raw_input("enter numbers, separated by space: ").split()
num_list = []

for token in strNum:
    try:
        num_list.append(int(token))
    except ValueError:
        # Do nothing, fetch the next token
        continue

print repr(num_list)

This code gives this result:

enter numbers, separated by space: 1 2 3 4 5 66
[1, 2, 3, 4, 5, 66]

enter numbers, separated by space: 1 2 3 4 5 66 asd 77
[1, 2, 3, 4, 5, 66, 77]

Strictly speaking the "continue" in the except clause is not necessary in
this simple example.

Hope this helps!

/dario
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111208/1d30f4a2/attachment.html>


More information about the Tutor mailing list