user6241246 user6241246 - 7 months ago 10
Python Question

Find substrings in string using python

I have data

vk.com/idefiks
vk.com/id211452033
vk.com/id211452033
vk.com/id165402000
vk.com/id_lizalizaelizaveta


I need to get all url, where are numbers after
id
.
If I use

if '/id' in url:


it returns all strings.
How can I return only
id
with number?

Answer

you can use re module. for example:

import re
s = """
vk.com/idefiks
vk.com/id211452033
vk.com/id211452033
vk.com/id165402000
vk.com/id_lizalizaelizaveta
"""
p = re.compile('/id\d+')
print p.findall(s)

The output will be:

['/id211452033', '/id211452033', '/id165402000']

PS: if want to remove / in the result, just update regular expression to /(id\d+). that is because, findall just returns the captured groups

Comments