Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In my opinion you have two options:</p> <ul> <li><p>Just try to convert it to an <code>int</code>, but catch the exception:</p> <pre><code>try: value = int(value) except ValueError: pass # it was a string, not an int. </code></pre> <p>This is the Ask Forgiveness approach.</p></li> <li><p>Explicitly test if there are only digits in the string:</p> <pre><code>value.isdigit() </code></pre> <p><a href="http://docs.python.org/2/library/stdtypes.html#str.isdigit"><code>str.isdigit()</code></a> returns <code>True</code> only if all characters in the string are digits (<code>0</code>-<code>9</code>).</p> <p>The <code>unicode</code> / Python 3 <code>str</code> type equivalent is <a href="https://docs.python.org/2/library/stdtypes.html#unicode.isdecimal"><code>unicode.isdecimal()</code></a> / <a href="https://docs.python.org/3/library/stdtypes.html#str.isdecimal"><code>str.isdecimal()</code></a>; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (<a href="http://codepoints.net/U+00B2">U+00B2 SUPERSCRIPT 2</a> is a digit, but not a decimal, for example).</p> <p>This is often called the Ask Permission approach, or Look Before You Leap. </p></li> </ul> <p>The latter will not detect all valid <code>int()</code> values, as whitespace and <code>+</code> and <code>-</code> are also allowed in <code>int()</code> values. The first form will happily accept <code>' +10 '</code> as a number, the latter won't.</p> <p>If your expect that the user <em>normally</em> will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload