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
How to Make Debian Package Install Dependencies
How to Fix Permission Denied for .Git/ Directory When Performing Git Push
Doesn't Sh Support Process Substitution <(...)
In Order to Write Pci Ethernet Driver. How to Implement Mmap in the Pci Ethernet Driver
Importing Shapefiles in Postgresql in Linux Using Pgadmin 4
Replacing Environment Variables in a Properties File
Enable/Disable Tasks in Crontab by Bash/Shell
Undefined Reference to 'Clock_Gettime' Although '-Lrt' Is Given
How Were the Weightings in the Linux Load Computation Chosen
Does Gcc, Icc, or Microsoft's C/C++ Compiler Support or Know Anything About Numa
How to Sleep in the Linux Kernel Space
How to Show Line Number When Executing Bash Script
How to Find Out Mount/Partition a Directory or File Is On? (Linux Server)
How to Sort Files Numerically from Linux Command Line
Count Occurrences of a Char in Plain Text File
Help with Understanding a Very Basic Main() Disassembly in Gdb