manlike
manlike

Reputation: 45

Python String .strip() function returning wrong output

I have the following string

'file path = data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif'

I am trying to get 256:0:10.0:34:26:-1478_B02_10m.tif from the string above

but if I run

os.path.splitext(filepath.strip('data/imagery/256:0:10.0:34:26:-1478'))[0]

It outputs '_B02_10m'

Same with filepath.rstrip('data/imagery/256:0:10.0:34:26:-1478')

Upvotes: 0

Views: 415

Answers (3)

BinarSkugga
BinarSkugga

Reputation: 397

Python's strip doesn't strip the string in the argument but uses it as a list of characters to remove from the original string see: https://docs.python.org/3/library/stdtypes.html#str.strip

EDIT: This doesn't provide a meaningful solution, see accepted answer.

Upvotes: 1

conmak
conmak

Reputation: 1470

Assuming you want all the string data after the / you can always use string.split. This spits your string into a list of strings split on the split string. Then you would only need the final item of this list.

string_var.split("/")[:-1]

See more official python docs on string.split here.

Upvotes: 1

Faheem Sharif
Faheem Sharif

Reputation: 246

Instead of using strip you should use string.split()

Following piece of code gets you the required substring:

filepath = "data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif"
print(filepath.split('/')[-1])

Output:

256:0:10.0:34:26:-1478_B02_10m.tif

Upvotes: 0

Related Questions