0

I want to strip the substring '_pf' from a list of strings. It is working for most of them, but not where there is a p in the part of the string I want to remain. e.g.

In: x = 'tcp_pf'
In: x.strip('_pf')
Out: 
'tc'

I would expect the sequence above to give an output of 'tcp'

Why doesn't it? Have i misunderstood the strip function?

doctorer
  • 1,672
  • 5
  • 27
  • 50
  • Carefully read the manual for the `strip` method: "If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on" – GWW May 26 '17 at 04:19
  • 2
    Have you tried consulting the [docs](https://docs.python.org/3/library/stdtypes.html#str.strip)? "The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped" – juanpa.arrivillaga May 26 '17 at 04:20
  • OK, I thought it would only strip the whole substring passed to it, rather than any of the characters within it. Is there an alternative function that does what I am trtying to do? – doctorer May 26 '17 at 04:21
  • You're right @Peter it's a duplicate. I should have looked harder. Should I delete it? – doctorer May 26 '17 at 05:21

2 Answers2

0

you can use:

x = 'tcp_ip'
x.split('_ip')[0]

Output:

'tcp'
Pavan
  • 108
  • 1
  • 12
-2

You can also use spilt function like below,

x.split('_pf')[0]

It will give you tcp.

manu
  • 321
  • 2
  • 8