-2

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']
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Kashew
  • 1
  • 2

3 Answers3

2

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]
broinjc
  • 2,619
  • 4
  • 28
  • 44
0

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 )
CAB
  • 1,106
  • 9
  • 23
0

The following should get your there.

def convert(x):
    try:
        return int(x)
    except ValueError:
        return x

aList = map(convert, aList)
Tammo Heeren
  • 1,966
  • 3
  • 15
  • 20