Change specific elements of a list from string to integers in python
<p>If I have a list such as </p>

<p><code>c=['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']</code></p>

<p>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 ?</p>

<p>expected output: </p>

<pre><code>`c=['my', 'age', 'is', 5,'The', 'temperature', 'today' 'is' ,87]`
</code></pre>

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

<p>Thank you. </p>

<p>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 <code>int()</code> on everything and see what succeeds or fails:</p>

<pre><code>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)
</code></pre>

<p>Generally using <code>try</code> and <code>except</code> 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 <code>int()</code>, or <code>float()</code>, can successfully handle, so the <code>try</code> approach is reasonable.</p>

python string list