I have the following string: string 1,2,100%,50% and I need to find numbers with percentages.

I tried this: x = re.search("\d+%","string 1,2,100%,50%") , but it finds only one ( 100% ).

What am I doing wrong?

    1 answer 1

    Use findall :

     text = 'string 1,2,100%,50%' import re print(re.findall("\d+%", text)) # ['100%', '50%'] 

    Option without regular:

     text = 'string 1,2,100%,50%' print([x for x in text.split()[1].split(',') if x.endswith('%')]) # ['100%', '50%'] # Используя filter items = list(filter(lambda x: x.endswith('%'), text.split()[1].split(','))) print(items) # ['100%', '50%'] text = 'string 1%,2,100%,50%' print([x for x in text.split()[1].split(',') if x.endswith('%')]) # ['1%', '100%', '50%'] 
    • If the text is 'string 1%,2,100%,50%' , then the variant without regular will work incorrectly. - insolor
    • @insolor, Yeah, but it's better to be guided by the current data, you can generally foresee all situations and the lexical parser will be released as a result :) and it will be something like: [x for x in text.split()[1].split(',') if x.endswith('%')] - gil9red