
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to extract numbers from a string in Python?
If you only want positive integers, you can split and search for numbers as follows:
>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog" >>> [int(s) for s in str.split() if s.isdigit()] [23, 11, 2]
For all other cases, using a regular expression would be the best choice. Also when extracting values, it'll be best to convert them to ints from string. For example:
>>> import re >>> [float(s) for s in re.findall(r'-?\d+\.?\d*', 'he33.45llo -42 I\'m a 32 string 30')] [33.45, -42.0, 32.0, 30.0]
- Related Articles
- How to extract numbers from a string using Python?
- Extract decimal numbers from a string in Python \n\n
- How to extract date from a string in Python?
- How to extract numbers from a string using regular expressions?
- How to extract a substring from inside a string in Python?
- Python – How to Extract all the digits from a String
- How to extract data from a string with Python Regular Expressions?
- Python – Extract Percentages from String
- How to extract numbers from text using Python regular expression?
- How to extract characters from a string in R?
- How can we extract the numbers from an input string in Java?
- Python Regex to extract maximum numeric value from a string
- Extract numbers from list of strings in Python
- How to extract date from string in MySQL?
- How to extract multiple integers from a String in Java?

Advertisements