Håkan Mjölk
Håkan Mjölk

Reputation: 73

How to convert string elements in a list into integers

I have this list:

new_list = ['a', '1', '--', '2', 'c', '3', 'd', '4', 'e' '5', 'f', '6', 'g', '7', 'h', '8', 'i']

It contains both numbers and words, however, the numbers are seen as strings and not integers. I want to convert the numbers from strings to integers. I tried with this myself:

for number in new_list:
    if number.isalpha():
        continue
    else:
        int(number) 

It looks through the list and if it's something with letters it continues, however, it doesn't work when it seems "special characters" such as the two lines on the third element. I get an error message there.

I also tried this:

for number, element in enumerate(lista_lista):
    if number.isalpha() == False:  
        int(number)

This only looks at every other element, which is a number, and uses isalpha(), and if that's False (which it should be), then I convert, but this doesn't work either.

Upvotes: 1

Views: 1249

Answers (6)

he below is a simple code without any error that you can use to fulfill your requirement, which is also easy to understand. Please have a check,

new_list = ['a','1','-','2','c','3','d','4','e','5','f','6','g','7','h','8','i']
for ind in range(len(new_list)):
    if new_list[ind].isdigit():
        new_list[ind]=int(new_list[ind])
    else:
        continue
print(new_list)

Upvotes: 2

SomeDude
SomeDude

Reputation: 14238

You can use str.isdigit and use list comprehension to modify like:

new_list = ['a', '1', '--', '2', 'c', '3', 'd', '4', 'e' '5', 'f', '6', 'g', '7', 'h', '8', 'i']

modified_list = [int(el) if el.isdigit() else el for el in new_list]

But it won't work for floats or negative integers in string form e.g. '-9', '11.5', if you need that you could do:

def convert_to_number(s):
    try:
        return int(s)
    except:
          try:
             return float(s)
          except:
                return s

new_list = ['a', '1', '--', '2', 'c', '3', 'd', '4', 'e' '5', 'f', '6', 'g', '7', 'h', '8', 'i' ,'-9', '11.5']

print([convert_to_number(el) for el in new_list])

Output:

['a', 1, '--', 2, 'c', 3, 'd', 4, 'e5', 'f', 6, 'g', 7, 'h', 8, 'i', -9, 11.5]

Upvotes: 1

Andreas
Andreas

Reputation: 9207

You can try this:

new_list = ['a', '1', '--', '2', 'c', '3', 'd', '4', 'e' '5', 'f', '6', 'g', '7', 'h', '8', 'i']

def to_int(x):
    try:
        return int(x)
    except:
        return x
        
[to_int(x) for x in new_list]
# Out[4]: ['a', 1, '--', 2, 'c', 3, 'd', 4, 'e5', 'f', 6, 'g', 7, 'h', 8, 'i']

This solution should be more performant than approaches like: int(x) if x.isdigit(), because you do not have to have call 2 different operations, like check if value is a digit and then apply the int conversion.

Upvotes: 2

zozo128
zozo128

Reputation: 59

Use isdigit instead:

[int(x) if x.isdigit() else x for x in new_list]

Upvotes: -1

Buddy Bob
Buddy Bob

Reputation: 5889

Go for something like this, using list comprehension.

old_list = ['a', '1', '--', '2', 'c', '3', 'd', '4', 'e' '5', 'f', '6', 'g', '7', 'h', '8', 'i']
new_list = [int(character) if character.isdigit() else character for character in old_list]

output

['a', 1, '--', 2, 'c', 3, 'd', 4, 'e5', 'f', 6, 'g', 7, 'h', 8, 'i']

Let's analyze your code.

for number in new_list:
    if number.isalpha():
        continue
    else:
        int(number) 

First of all, you iterate through new_list correctly. Now you also check if number is an alphabet that is correct. But you need to take action on that. Instead, you use continue. I suggest appending number to a list. Say it is not an alphabet, we try and turn number into an int. Sure, this works out. But your new_list will not change. Instead, you'd probably want to append number to a list. One problem I've spotted is, what if a character in the list is --. This is not an alphabet and not an integer. So by default, we will move to the else and try and perform int('--') which will return an error. So using .isdigit() is the best bet.

Upvotes: 0

Barmar
Barmar

Reputation: 782498

Use number.isdigit() to recognize the numeric elements. Just because it's not alphabetic, it doesn't mean it's a number.

list_with_numers = [int(x) if x.isdigit() else x for x in new_list]

Upvotes: 4

Related Questions