Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting subset of strings to integers in a list

Tags:

python

I frequently find myself with a list that looks like this:

lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']

What is the most pythonic way to convert specific strings in this list to ints?

I typically do something like this:

lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]

The above approach seems wrong. Are there better way to convert only certain items in lists to integers?

like image 249
turtle Avatar asked Mar 02 '13 22:03

turtle


People also ask

How do I convert a list of strings to a list of integers in Python?

To convert a list of strings to a list of integers: Pass the int() class and the list to the map() function. The map() function will pass each item of the list to the int() class. The new list will only contain integer values.

How do we convert a string value into a list?

To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.

How do you convert a list of data to integers in Python?

Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.


2 Answers

I would say something like:

>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> lst = [int(s) if s.isdigit() else s for s in lst]
>>> lst
['A', 1, 2, 'B', 1, 'C', 'D', 4, 1, 4, 5, 'Z', 'D']
like image 95
FatalError Avatar answered Sep 19 '22 16:09

FatalError


int and .isdigit can disagree in Unicode case i.e., int might fail to parse a string even if .isdigit returns True for the string.

def maybe_int(s):
    try:
        return int(s)
    except ValueError:
        return s

lst = [maybe_int(s) for s in lst]
like image 23
jfs Avatar answered Sep 18 '22 16:09

jfs