[Tutor] how to use int and split() simultaneously
शंतनू
shantanoo at gmail.com
Thu Dec 8 21:33:03 CET 2011
On 08-Dec-2011, at 7:13 PM, Dario Lopez-Kästen wrote:
> 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
>
Using re module:
===
import re
strNum = raw_input("enter numbers, separated by space: ")
if re.search('[^\d ]', strNum):
print('Invalid input')
else:
data = [int(x) for x in strNum.split()]
print(data)
===
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111209/16af627e/attachment.html>
More information about the Tutor
mailing list