[Tutor] how to use int and split() simultaneously
Steven D'Aprano
steve at pearwood.info
Thu Dec 8 23:06:56 CET 2011
शंतनू wrote:
> 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)
This is not Perl, where everything is a nail that needs to be hammered with a
regex. Especially not a regex which is wrong: your regex is too strict. It
disallows using tabs as separators, while str.split() will happily consume
tabs for you.
In general, in Python, the way to check of an error condition is to try it,
and if it fails, catch the exception. This doesn't always apply, but it does
apply most of the time.
data = [int(x) for x in strNum.split()]
will print a perfectly good error message if it hits invalid input. There's no
need to check the input first with a regex. If you want to recover from
errors, it is easy by taking the conversion out of a list comprehension and
into an explicit for loop:
data = []
for s in strNum.split():
try:
data.append(int(s))
except ValueError:
data.append(42) # Or some other default value.
If you don't care about recovering from individual errors, but only care
whether the entire conversion succeeds or fails:
try:
data = [int(s) for s in strNum.split()]
except ValueError:
data = []
--
Steven
More information about the Tutor
mailing list