0

Given this list:

>>> a = "123DJY65TY"
>>> list(a)
['1','2','3','D','J','Y','6','5','T','Y']

How can I produce a list where integers are not treated as strings? Like this:

[1,2,3,'D','J','Y',6,5,'T','Y']   
Will
  • 24,082
  • 14
  • 97
  • 108
Shreya Gaddam
  • 33
  • 1
  • 8
  • Take a look to [this](http://stackoverflow.com/a/961661/3077939) for conversion from string to int. – aluriak Jun 03 '16 at 07:56

2 Answers2

5

You can use list comprehension and str.isdigit to convert each character that is a digit:

>>> a = "123DJY65TY"
>>> [int(x) if x.isdigit() else x for x in a]
[1, 2, 3, 'D', 'J', 'Y', 6, 5, 'T', 'Y']
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

You can convert all strings in a list containing only digits this way, using map() and str.isdigit():

a = map(lambda char: int(char) if char.isdigit() else char, list(a))

For example:

In [3]: a = map(lambda char: int(char) if char.isdigit() else char, list(a))

In [4]: a
Out[4]: [1, 2, 3, 'D', 'J', 'Y', 6, 5, 'T', 'Y']

@niemmi's solution using list comprehensions is probably a better approach given that we start with a string, not a list.

Will
  • 24,082
  • 14
  • 97
  • 108