I have a list:
aList = ['asdf123', '100', '45', '34hello']
how can I change it so the '100' and '45' becomes int rather than str?
aList = ['asdf123', 100, 45, '34hello']
I have a list:
aList = ['asdf123', '100', '45', '34hello']
how can I change it so the '100' and '45' becomes int rather than str?
aList = ['asdf123', 100, 45, '34hello']
You could use a helper function,
def to_int(s):
try:
return int(s)
except:
return s
aList = [to_int(n) for n in aList]
Define a method which will convert an integer or return the original value;
def tryInt(value):
try:
return int(value)
except:
return value
Then use map
and lambda
;
map( lambda x: tryInt(x), aList )
The following should get your there.
def convert(x):
try:
return int(x)
except ValueError:
return x
aList = map(convert, aList)