Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use text strip() function?

I can strip numerics but not alpha characters:

>>> text
'132abcd13232111'

>>> text.strip('123')
'abcd'

Why the following is not working?

>>> text.strip('abcd')
'132abcd13232111'
like image 734
Vic Avatar asked Apr 16 '26 21:04

Vic


2 Answers

The reason is simple and stated in the documentation of strip:

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. 
The chars argument is a string specifying the set of characters to be removed.

'abcd' is neither leading nor trailing in the string '132abcd13232111' so it isn't stripped.

like image 87
Dimitris Fasarakis Hilliard Avatar answered Apr 19 '26 10:04

Dimitris Fasarakis Hilliard


Just to add a few examples to Jim's answer, according to .strip() docs:

  • Return a copy of the string with the leading and trailing characters removed.
  • The chars argument is a string specifying the set of characters to be removed.
  • If omitted or None, the chars argument defaults to removing whitespace.
  • The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.

So it doesn't matter if it's a digit or not, the main reason your second code didn't worked as you expected, is because the term "abcd" was located in the middle of the string.


Example1:

s = '132abcd13232111'
print(s.strip('123'))
print(s.strip('abcd'))

Output:

abcd
132abcd13232111

Example2:

t = 'abcd12312313abcd'
print(t.strip('123'))
print(t.strip('abcd'))

Output:

abcd12312313abcd
12312313
like image 32
dot.Py Avatar answered Apr 19 '26 10:04

dot.Py