How to Extract Numbers from a String

How to extract numbers from a string in Python?

If you only want to extract only positive integers, try the following:

>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]

I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.

This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.

Extract Number from String in Python

You can filter the string by digits using str.isdigit method,

>>> int(filter(str.isdigit, str1))
3158

Is there a better way to extract numbers from a string in python 3

Here's one way you can do the regex search that @Barmar suggested:

>>> import re
>>> int(re.search("\d+", "V70N-HN")[0])
70

Extract digits from string - StringUtils Java

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");

Extracting numbers from vectors of strings

How about

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

or

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

or

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))

How to extract numbers from mixed strings

We can use parse_number

library(readr)
parse_number(figc)
[1] 3 2 7 8 10 3 4 6 3 3 5 9 1 13 15 18 21 22 5 6 9 1 13 14 15

data

figc <- c("3", "2", "7", "8", "10", "3", "4", "6", "P3a", "P3b", "5", 
"P9", "1", "13", "15", "18", "21", "22", "5", "6", "9", "1",
"13", "14", "15")


Related Topics



Leave a reply



Submit