Reputation: 183
This sounds so simple, but I cannot find anything on how to do this on the internet. I've gone through documentation but that didn't help me.
I have to get inputs from the user to create a list. This is what I am using right now.
t = raw_input("Enter list items: ")
l = map(str,t.split())
But this is converting every element into a string. If I use int in map function, then every element would be converted to int.
What should I do? Is there any other function that I am missing?
Upvotes: 0
Views: 263
Reputation: 23827
use try/except. Try to make it an int. If that fails, leave it as a string.
def operation(str):
try:
val = int(str)
except ValueError:
val = str
return val
t = raw_input("Enter list items: ")
l = map(operation,t.split())
print l
You can use a list comprehension rather than map for more "pythonic" code:
t = raw_input("Enter list items: ")
l = [operation(x) for x in t.split()]
Edit: I like iCodez's better... the isDigit test is nicer than try except.
Upvotes: 1
Reputation:
You can use a list comprehension to only call int
on the strings which contain nothing but numerical characters (this is determined by str.isdigit
):
t = raw_input("Enter list items: ")
l = [int(x) if x.isdigit() else x for x in t.split()]
Demo:
>>> t = raw_input("Enter list items: ")
Enter list items: 1 hello 2 world
>>> l = [int(x) if x.isdigit() else x for x in t.split()]
>>> l
[1, 'hello', 2, 'world']
>>>
Upvotes: 1