john john - 5 months ago 21
Python Question

Change specific elements of a list from string to integers in python

If I have a list such as

c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']

How do I specifically Convert the numbers of the the list into integers leaving the rest of the string as it is and get rid of the \n ?

expected output:

`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]`

I tried using the 'map()' and 'isdigit()' function but it didnt work.

Thank you.


If you don't know the format of integers in your text, or there are just too many variations, then one approach is simply to try int() on everything and see what succeeds or fails:

original = ['my', 'age', 'is', '5\n', 'The', 'temperature', 'today', 'is', '87\n']
revised = []

for token in original:
    except ValueError:


Generally using try and except as part of your algorithm, not just your error handling, is a bad practice, since they aren't efficient. However, in this case, it's too hard to predict all the possible inputs that int(), or float(), can successfully handle, so the try approach is reasonable.