Reputation: 192
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.
Upvotes: 1
Views: 363
Reputation: 41872
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:
try:
revised.append(int(token))
except ValueError:
revised.append(token)
print(revised)
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.
Upvotes: 1
Reputation: 30258
You can write a function that tries to convert to an int
and if it fails return the original, e.g:
def conv(x):
try:
x = int(x)
except ValueError:
pass
return x
>>> c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']
>>> list(map(conv, c))
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
>>> [conv(x) for x in c]
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
Note: 2 strings separated by whitespace are automatically concatenated by python, e.g. 'today' 'is'
is equivalent to 'todayis'
Upvotes: 1