0

I have a list of strings:

strings = ['stability', 'of', 'the', 'subdural', 'hematoma', 'she', 'was', 'transferred', 'to', 'the', 'neurosciences', 'floor', 'on', '3', '8', 'after', '24', 'hours', 'of', 'close']

Whats the best way to iterate over the list, detect the numbers and change the type of the element to an int?

In this particular example, strings[13], strings[14] and strings[16], should be recognized as numbers and converted from type str to type int.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Carlos Muñiz
  • 1,598
  • 7
  • 23
  • 28

1 Answers1

3

Use a try/except with a list comp, trying to cast to int and catching any ValueErrors just returning each element in the except when you do:

def cast(x):
    try: 
        return int(x)
    except ValueError:
        return x
strings[:] =  [cast(x) for x in strings]

output:

['stability', 'of', 'the', 'subdural', 'hematoma', 'she', 'was', 
'transferred', 'to', 'the', 'neurosciences', 'floor', 'on', 3, 8, 
'after', 24, 'hours', 'of', 'close']

If you only had positive integers you could use str.isdigit:

strings[:] =  [int(x) if x.isdigit() else x for x in strings]

The output would be the same but isdigit would not work for any negative numbers or "1.0" etc.. Using strings[:] = ... just means we change the original object/list.

Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312