[英]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
. 我需要获取所有url, id
后面的数字在哪里。 If I use 如果我用
if '/id' in url:
it returns all strings. 它返回所有字符串。 How can I return only id
with number? 如何只返回id
和数字?
you can use re
module. 您可以使用re
模块。 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+)
. PS:如果要在结果中删除/
,只需将正则表达式更新为/(id\\d+)
。 that is because, findall
just returns the captured groups 这是因为, findall
仅返回捕获的组
Simplest solution : 最简单的解决方案:
x = "vk.com/idefiks"
x[6:]
This will give : /idefiks
这将给: /idefiks
If you want to omit the /
use x[7:]
. 如果要省略/
使用x[7:]
。
You may do it using re
too, but that's not required for this case. 您也可以使用re
来做到这一点,但是在这种情况下不是必需的。
if '/id' in url:
result = url.split('/id')[-1]
for item in data:
listItem = item.split('/')
strId = listItem[1]
try this 尝试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.