Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Wednesday 1st February 2012
Last Updated: Wednesday 29th December 2021

Edit 1: This article has been revised to show the differences between str.isdigit() and the custom solution provided.
Edit 2: The sample also supports Unicode!

Often you will want to check if a string in Python is a number. This happens all the time, for example with user input, fetching data from a database (which may return a string), or reading a file containing numbers. Depending on what type of number you are expecting, you can use several methods. Such as parsing the string, using regex, or simply attempting to cast (convert) it to a number and see what happens. Often you will also encounter non-ASCII numbers, encoded in Unicode. These may or may not be numbers. For example ๒, which is 2 in Thai. However © is simply the copyright symbol, and is obviously not a number.

Note that if you are executing the following code in Python 2.x, you will have to declare the encoding as UTF-8/Unicode - as follows:
[python]
# -*- coding: utf-8 -*-
[/python]

The following function is arguably one of the quickest and easiest methods to check if a string is a number. It supports str, and Unicode, and will work in Python 3 and Python 2.

Checking if a Python String is a Number

[python]
def is_number(s):
try:
float(s)
return True
except ValueError:
pass

try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass

return False
[/python]

When we test the function, we get the following:



[python]
>>> # Testing as a str
>>> print(is_number('foo'))
False
>>> print(is_number('1'))
True
>>> print(is_number('1.3'))
True
>>> print(is_number('-1.37'))
True
>>> print(is_number('1e3'))
True
>>>
>>> # Testing Unicode
>>> # 5 in Arabic
>>> print(is_number('Ù¥'))
True
>>> # 2 in Thai
>>> print(is_number('๒'))
True
>>> # 4 in Japanese
>>> print(is_number('å››'))
True
>>> # Copyright Symbol
>>> print(is_number('©'))
False
[/python]


[python]
>>> # Testing as a str
>>> print(is_number('foo'))
False
>>> print(is_number('1'))
True
>>> print(is_number('1.3'))
True
>>> print(is_number('-1.37'))
True
>>> print(is_number('1e3'))
True
>>>
>>> # Testing Unicode
>>> # 5 in Arabic
>>> print(is_number(u'Ù¥'))
True
>>> # 2 in Thai
>>> print(is_number(u'๒'))
True
>>> # 4 in Japanese
>>> print(is_number(u'å››'))
True
>>> # Copyright Symbol
>>> print(is_number(u'©'))
False
[/python]

We first try to simply convert/cast it to a float, and see what happens. This will work for the str and Unicode data types when the string is not strictly Unicode. However we also try to convert the string using the unicodedata module. What does the unicodedata.numeric function do? Well some Unicode characters have numeric attributes assigned to them, if they are a number. The unicodedata.numeric will simply return the numeric value of the character, if it exists. You may assign a default value for unicodedata.numeric to return if there is no numeric attribute, otherwise by default a ValueError will be raised.

Checking if a Python String is a Digit in Python (str.isdigit)

Python has a handy built-in function, str.isdigit, that lets you check if a string is a digit.

Numbers versus Digits

Be sure that when you use the str.isdigit function, you are really checking for a digit and not an arbitrary number. The definition of digit according to the Python documentation is as follows:

Return true if all characters in the string are digits and there is at least one character, false otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits.
https://docs.python.org/3/library/stdtypes.html#str.isdigit

Here's an example:

[python]
>>> print('foo'.isdigit())
False
>>> print('baz'.isdigit())
False
>>> print('1'.isdigit())
True
>>> print('36'.isdigit())
True
>>> print('1.3'.isdigit())
False
>>> print('-1.37'.isdigit())
False
>>> print('-45'.isdigit())
False
>>> print('1e3'.isdigit())
False
[/python]

Latest Articles


Tags

  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Python is a beautiful language.