'Python - How to get only the numbers from a string which has got commas in between
Consider like I have a string :
stringA = "values-are-10,20,30,40,50"
stringB = "values-are-10"
I need to get only the strings : desired output :
for stringA: 10,20,30,40,50
for stringB: 10
I tried using this - int(''.join(filter(str.isdigit, stringA)))
But it removed all the commas, please let me know how to get the output in that format.
Solution 1:[1]
Using re.findall here is your friend:
stringA = "values-are-10,20,30,40,50"
stringB = "values-are-10"
strings = [stringA, stringB]
output = [re.findall(r'\d+(?:,\d+)*', s)[0] for s in strings]
print(output) # ['10,20,30,40,50', '10']
Solution 2:[2]
[int(v) for v in stringA.rsplit("-", 1)[-1].split(",")]
rsplit splits from the right - all numbers appear after the last "-". Then we split by ","
Solution 3:[3]
If it's guaranteed that the initial string will always have the format,
prefix + values, why not just substring this out, a simple
stringA, stringB = stringA[len(prefixA):], stringB[len(prefixB):];
and then,
list1, list2 = [int(num) for num in stringA.split(',')], [int(num) for num in stringB.split(',')];
should do the job...
Solution 4:[4]
# Add regex package
import re
stringA = "values-are-10,20,30,40,50"
stringB = "values-are-10"
#search using regex
A = re.findall('[0-9]+', stringA)
print(A) # ['10', '20', '30', '40', '50']
B = re.findall('[0-9]+', stringB)
print(B) # ['10']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | kwsp |
| Solution 3 | Hiten Tandon |
| Solution 4 | Pranav Hosangadi |
