Reputation: 2292
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
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
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
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
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