title: How to extract a number from a string in Python?
body: <p>How do you extract a number from a string to be able to manipulate it? The number could be either an <code>int</code> or a <code>float</code>. For example if the string is <code>"flour, 100, grams"</code> or <code>"flour, 100.5, grams"</code> then extracting the number <code>100</code> or <code>100.5</code>.</p>
  
  <p><strong>Code</strong>:</p>
  
  <pre><code>string  = "flour, 100, grams"
  numbers = [int(x) for x in string.split(",")]
  print(numbers)
  </code></pre>
  
  <p><strong>Output</strong>:</p>
  
  <pre><code>Traceback (most recent call last):
    File "/Users/lewis/Documents/extracting numbers.py", line 2, in &lt;module&gt;
      numbers = [int(x) for x in string.split(",")]
   File "/Users/lewis/Documents/extracting numbers.py", line 2, in &lt;listcomp&gt;
     numbers = [int(x) for x in string.split(",")]
  ValueError: invalid literal for int() with base 10: 'flour'
  </code></pre>