开发者

Python string extraction

开发者 https://www.devze.com 2023-01-29 09:48 出处:网络
In th开发者_Python百科e following string how to get the id after the directory media and after getting the id ignore the rest of the string to read only the id numbers

In th开发者_Python百科e following string how to get the id after the directory media and after getting the id ignore the rest of the string to read only the id numbers

id_arr= ["/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"]

The output should be 12 24 26 56


If the strings always look the way you said, try

ids = [int(s.split("/")[3]) for s in id_arr]


>>> import re
>>> myre = re.compile("^.*/media/(\d+)")
>>> for item in id_arr:
...     print (myre.search(item).group(1))
...
12
24
26
56


[x.split('/')[3] for x in id_arr]


The correct way probably involves some clever use of the os.path module, but for the input given, just use a regex for media\/([0-9]+) and extract the first group.


parts = "/opt/media/12/htmls","/opt/media/24/htmls","/opt/media/26/htmls","/opt/media/56/htmls"
for str in parts:
    print str.split("/")[3]

EDIT: unuseful rpartition() removed

0

精彩评论

暂无评论...
验证码 换一张
取 消