开发者

Python string extraction

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜