Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find multiple strings between chars

I have a long string with data like this:

category: 33 ; id: AF45DA; category: 54 ; id: KF65YA; category: 60 ; id: XC36IA;

And I would like to create list from it that look like this:

new_list = [33,54,60]

Basically I just need the values between the category: and ; in a string while keeping the original order.

I could create something that seems working I assume there can be exceptions when it won't work correctly. I'm new to Python and don't really know the possibilities.

This is the actual version:

s = "category: 33 ; id: AF45DA; category: 54 ; id: KF65YA; category: 60 ; id: XC36IA;"
c = s.count("category")
z = 0
number_list = []
for x in range(z,c):
    val = s.split('category:')[x+1]
    number = val.split(' ;')[0]
    print (number)
    number_list.append(number.strip())

print ("All Values:", number_list)
like image 770
rihe Avatar asked Jun 15 '26 04:06

rihe


1 Answers

Simply construct a regex:

import re

rgx = re.compile(r'category:\s*(\d+)\s*;')
number_list = rgx.findall('category: 33 ; id: AF45DA; category: 54 ; id: KF65YA; category: 60 ; id: XC36IA;')

This gives:

>>> rgx.findall('category: 33 ; id: AF45DA; category: 54 ; id: KF65YA; category: 60 ; id: XC36IA;')
['33', '54', '60']

If you want the result to be ints, you can use a map:

import re

rgx = re.compile(r'category:\s*(\d+)\s*;')
number_list = list(map(int,rgx.findall('category: 33 ; id: AF45DA; category: 54 ; id: KF65YA; category: 60 ; id: XC36IA;')))

This produces:

>>> number_list
[33, 54, 60]
like image 132
Willem Van Onsem Avatar answered Jun 18 '26 00:06

Willem Van Onsem