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']
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']
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']
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.