Separate an ordered sequence of characters from a string

I recently realized that the inline strip inline Python (and its children rstrip and lstrip ) does not process the string that is assigned to it as an argument as an ordered sequence of characters, but instead as a kind of β€œreservoir” of characters:

 >>> s = 'abcfooabc' >>> s.strip('abc') 'foo' >>> s.strip('cba') 'foo' >>> s.strip('acb') 'foo' 

etc.

Is there a way to remove an ordered substring from a given string so that the result is different in the examples above?

+6
source share
3 answers

I don’t know the built-in way, no, but it is pretty simple:

 def strip_string(string, to_strip): if to_strip: while string.startswith(to_strip): string = string[len(to_strip):] while string.endswith(to_strip): string = string[:-len(to_strip)] return string 
+4
source

I had the same problem when I was just starting out.

Try str.replace instead <

 >>> s = 'abcfooabc' >>> s.replace("abc", "") 0: 'foo' >>> s.replace("cba", "") 1: 'abcfooabc' >>> s.replace("acb", "") 2: 'abcfooabc' 
+2
source

How about this: s.split('abc') .

This returns: ['', 'foo', ''] .

So we can change it to:

[i for i in s.split('abc') if i != ''] . If you want only 'foo' and not ['foo'] , you can do: [i for i in s.split('abc') if i != ''][0] .

Together:

 def splitString(s, delimiter): return [i for i in s.split(delimiter) if i != ''][0] 
0
source

All Articles