wanderors
wanderors

Reputation: 2292

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.

Upvotes: 1

Views: 103

Answers (4)

Devesh
Devesh

Reputation: 613

# 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']

Upvotes: 0

Hiten Tandon
Hiten Tandon

Reputation: 64

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...

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521168

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']

Upvotes: 2

user12734467
user12734467

Reputation:

[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 ","

Upvotes: 1

Related Questions