Logo

Programming-Idioms

  • PHP
  • C++
  • Python

Idiom #137 Check if string contains only digits

Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.

try:
  int(s)
  b = true
except:
  b = false
b = s.isdigit()

Here digits are characters having Numeric_Type=Digit or Numeric_Type=Decimal, this is not exactly the range '0'..'9'.
Returns false if s is empty.
from string import digits
b = all(x in digits for x in s)
$b = preg_match('/\D/', $s) !== 1;
#include <algorithm>
#include <cctype>
#include <string>
bool b = false;
if (! s.empty() && std::all_of(s.begin(), s.end(), [](char c){return std::isdigit(c);})) {
    b = true;
}

s must be a std::string
B := (for all Char of S => Char in '0' .. '9');

New implementation...
< >
programming-idioms.org