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>You can write a function that tries to convert to an <code>int</code> and if it fails return the original, e.g:</p>

<pre><code>def conv(x):
    try:
        x = int(x)
    except ValueError:
        pass
    return x

&gt;&gt;&gt; c = ['my', 'age', 'is', '5\n','The', 'temperature', 'today' 'is' ,'87\n']
&gt;&gt;&gt; list(map(conv, c))
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
&gt;&gt;&gt; [conv(x) for x in c]
['my', 'age', 'is', 5, 'The', 'temperature', 'todayis', 87]
</code></pre>

<p>Note: 2 strings separated by whitespace are automatically concatenated by python, e.g. <code>'today' 'is'</code> is equivalent to <code>'todayis'</code></p>

python string list