Rajeev
Rajeev

Reputation: 46899

Python string extraction

In the 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

Upvotes: 0

Views: 865

Answers (5)

Vincenzo Pii
Vincenzo Pii

Reputation: 19805

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

Upvotes: 0

Wang
Wang

Reputation: 3347

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.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336088

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

Upvotes: 3

Jan B. Kjeldsen
Jan B. Kjeldsen

Reputation: 18051

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

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601361

If the strings always look the way you said, try

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

Upvotes: 3

Related Questions