bbartling
bbartling

Reputation: 3494

python strings strip characters

How can I strip away only the charactersdevices/ from a string devices/slipstream_internal/slipstream_hq/23?

If I try:

device = 'devices/slipstream_internal/slipstream_hq/23'
device = device.strip('devices/')

print(device)

why does this print as lop off the s in slipstream_internal that I want? This prints:

'lipstream_internal/slipstream_hq/23'

I am using Python 3.8

Upvotes: 0

Views: 102

Answers (3)

azro
azro

Reputation: 54148

Problem

The str.strip method remove, from beginning, any char that is contained in the the given parameter, no matter the order, until one isn't in the given values, so these calls are identical

device.strip('devices/')
device.strip('/devices')
device.strip('/cdsiev')

It contains an s, so the s is removed


Solution

  • use re.sub with '^devices/' (the ^ in pattern ensures it removes only frmo beginning)

    import re
    device = 'devices/slipstream_internal/slipstream_hq/23'
    device = re.sub('^devices/', '', device)
    
  • str.replace with count of 1, but can remove not beginning value

    device = device.replace('devices/', '', 1)
    
  • Or str.removeprefix from python3.9

    device = device.removeprefix('devices/')
    

Upvotes: 4

Bill the Lizard
Bill the Lizard

Reputation: 405735

strip('devices/') will remove any of the characters that you pass as an argument from the beginning and end of a string. Think of the argument as a set of characters to remove, not as a substring or sequence to remove.

If you just want to remove 'devices/' from the beginning of the string, try using

device.replace('devices/', '')

or even better

device.replace('devices/', '', 1)

to make sure only the first occurrence is removed.

Upvotes: 1

Gustavo Penna
Gustavo Penna

Reputation: 1

You might want to use a string replace function.

device = 'devices/slipstream_internal/slipstream_hq/23'
device = device.replace('devices/', '')

print(device)

Upvotes: 0

Related Questions