How to get everything after string x in python

Viewed 358

I have a string:

s3://tester/test.pdf

I want to exclude s3://tester/ so even if i have s3://tester/folder/anotherone/test.pdf I am getting the entire path after s3://tester/

I have attempted to use the split & partition method but I can't seem to get it.

Currently am trying:

string.partition('/')[3]

But i get an error saying that it out of index.

EDIT: I should have specified that the name of the bucket will not always be the same so I want to make sure that it is only grabbing anything after the 3rd '/'.

4 Answers

Have you tried .replace?

You could do:

string = "s3://tester/test.pdf"
string = string.replace("s3://tester/", "")
print(string)

This will replace "s3://tester/" with the empty string ""

Alternatively, you could use .split rather than .partition

You could also try:

string = "s3://tester/test.pdf"
string = "/".join(string.split("/")[3:])
print(string)

You can use str.split():

path = 's3://tester/test.pdf'
print(path.split('/', 3)[-1])

Output:

test.pdf

UPDATE: With regex:

import re
path = 's3://tester/test.pdf'
print(re.split('/',path,3)[-1])

Output:

test.pdf

To answer "How to get everything after x amount of characters in python"

string[x:]

PLEASE SEE UPDATE

ORIGINAL Using the builtin re module.

p = re.search(r'(?<=s3:\/\/tester\/).+', s).group()

The pattern uses a lookbehind to skip over the part you wish to ignore and matches any and all characters following it until the entire string is consumed, returning the matched group to the p variable for further processing.

This code will work for any length path following the explicit s3://tester/ schema you provided in your question.

UPDATE

Just saw updates duh.

Got the wrong end of the stick on this one, my bad.

Below re method should work no matter S3 variable, returning all after third / in string.

p = ''.join(re.findall(r'\/[^\/]+', s)[1:])[1:]
Related