in python wants to take certain part from a given string

Viewed 46

I have a string type URL --https://drive.google.com/file/d/1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82/view?usp=sharing I want only part after "d/" and before "/view" from the above string so how can I use it using regex or any other function example I only want 1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82 from the above string using python. now I am using this a =df['image'] for i in a : print(type(i))

res=re.findall('/d/(.*)/view', i)
print(res)

but getting blank array res while printing it

3 Answers

I guess /d/(.*)/view is the regex you are looking for. re.findall('/d/(.*)/view', url)[0] works with your example.

import re
s="--https://drive.google.com/file/d/1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82/view?usp=sharing"
res=re.findall('/d/(.*)/view', s)
if len(res)==0:
    print('bad url')
else:
    print(res[0])

ADDITION (example using dataframes)

import pandas as pd
import re
df=pd.DataFrame([["url1", "--https://drive.google.com/file/d/1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82/view?usp=sharing"], ["url2", "--https://drive.google.com/file/d/second/one/view?usp=sharing"], ["noUrl", "anotherstring"]], columns=['name', 'image'])

df is this dataframe

Then

for i in df['image']:
    res=re.findall('/d/(.*)/view', i)
    print(res)

output

['1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82']
['second/one']
[]

as expected. A len(res)=1 array whose res[0] element is the pattern you want if it matches, or an empty array if not. If you have more than one /d/.../view patter in your url, then you may even have a longer than 1 answer. But empty one is only if you don't have a .../d/.../view... form

You can utilize str.split method. First split the string using "/d/" and then use second part and split based on "/view". Take the first part of the new string.

html.split("/d/")[1].split("/view")[0]

If your string is always going to look like this, I would break the string apart using the "/" as a delimiter.

s = "https://drive.google.com/file/d/1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82/view?usp=sharing"
s = s.split('/')[5]
Related