Str.Strip() Strange Behavior

str.strip() strange behavior

strip(".gz") removes any of the characters ., g and z from the beginning and end of the string.

Strange behaviour of Python strip function

You've misunderstood strip() - it removes any of the specified characters from both ends; there is no regex support here.

You're asking it to strip both . and 0 off both ends, so it does - and gets left with 55.

See the official String class docs for details.

Strange Python strip() behavior

The string passed to strip is treated as a bunch of characters, not a string. Thus, strip('Axyx') means "strip occurrences of A, x, or y from either end of the string".

If you actually want to strip a prefix or suffix, you'd have to write that logic yourself. For example:

s = 'Abcd Efgh Axyx'
if s.endswith('Axyx'):
s = s[:-len('Axyx')]

Weird behavior of strip()

The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).

The characters that are in df, they occur at the end in the string adf. This is not the case in string xc where the first and last character are ! and d.

str.strip([chars]); => If any character in str occurs in chars at last or first index, then that character is stripped off from str. Then it again checks. When no character is stripped, it stops.

Python string.strip() shows weird behaviour

You can use replace to achieve what you wanted to do.

>>> string.replace('H:\\Jupyter\\SAF_Prewfdsds\\Testings_05601252\\050_7_150_', '')
'PYPL.csv'

This will replace the first arg with the second arg

Python - an extremely odd behavior of function lstrip

You're misunderstanding how lstrip works. It treats the characters you pass in as a bag and it strips characters that are in the bag until it finds a character that isn't in the bag.

Consider:

'abc'.lstrip('ba')  # 'c'

It is not removing a substring from the start of the string. To do that, you need something like:

if s.startswith(prefix):
s = s[len(prefix):]

e.g.:

>>> s = 'foobar'
>>> prefix = 'foo'
>>> if s.startswith(prefix):
... s = s[len(prefix):]
...
>>> s
'bar'

Or, I suppose you could use a regular expression:

>>> s = 'foobar'
>>> import re
>>> re.sub('^foo', '', s)
'bar'

Odd bug in string.strip() using python 2.7 and 3.5

This is how the strip method is actually designed to work.

The chars argument is a string specifying the set of characters to be removed.

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

So when you say my_string.strip('.pools'), it's going to remove all leading and trailing characters in that set (ie. {'.', 'p', 'o', 'l', 's'}).

You probably want to use str.replace or re.sub.

>>> './omqbEXPT.pool'.replace('./', '').replace('.pool', '')
'omqbEXPT'

>>> import re
>>> re.sub(r'^\.\/|\.pool$', '', './omgbEXPT.pool')
'omqbEXPT'


Related Topics



Leave a reply



Submit