Extract a number of continuous digits from a random string in python
Question: I am trying to parse this list of strings that contains ID values as a series
of 7 digits but I am not sure how to approach this.

    
    
    lst1=[
        "(Tower 3rd fl floor_WINDOW CORNER : option 2_ floor cut out_small_wood) : GA -   
    Floors : : Model Lines : id 3925810 
    (Tower 3rd fl floor_WINDOW CORNER : option 2_ floor cut out_small_wood) : GA - Floors : Floors : Floor : Duke new core floors : id 3925721",
            "(Tower 3rd fl floor_WINDOW CORNER : option 3_ floor cut out_large_wood) : GA - Floors : : Model Lines : id 3976019 
    (Tower 3rd fl floor_WINDOW CORNER : option 3_ floor cut out_large_wood) : GA - Floors : Floors : Floor : Duke new core floors : id 3975995"
            ]
    

I really want to pull out just the digit values and combine them into one
string separated by a colon ";". The resulting list would be something like
this:

    
    
    lst1 = ["3925810; 3925721", "3976019; 3975995"]
    


Answer: You can use regular expression, like this

    
    
    import re
    pattern = re.compile(r"\bid\s*?(\d+)")
    print ["; ".join(pattern.findall(item)) for item in lst1]
    # ['3925810; 3925721', '3976019; 3975995']
    

![Regular expression
visualization](https://www.debuggex.com/i/WjsdMuFf3Ajy4sfR.png)

[Debuggex Demo](https://www.debuggex.com/r/WjsdMuFf3Ajy4sfR)

If you want to make sure that the numbers you pick will only be of length 7,
then you can do it like this

    
    
    pattern = re.compile(r"\bid\s*?(\d{7})\D*?")
    

![Regular expression
visualization](https://www.debuggex.com/i/4fFYJ9l06fEJScay.png)

[Debuggex Demo](https://www.debuggex.com/r/4fFYJ9l06fEJScay)

The `\b` refers to the word boundary. So, it makes sure that `id` will be a
separate word and it is followed by 0 or more whitespace characters. And then
we match numeric digits `[0-9]`, `\d` is just a shorthand notation for the
same. `{7}` matches only seven times and followed by `\D`, its the inverse of
`\d`.

