Search code examples
pythonstringsplitstrip

Why split and strip gives different output in python?


I was trying to extract the state name from the string 'Rhode Island[edit]'.

When I tried .split('[[]').str[0], I was given the correct result 'Rhode Island'. However, when I tried .rstrip('[edit]'), I was given the wrong result 'Rhode Islan'.

I got confused why the character 'd' before the left bracket was also removed when I used rstrip function.


Solution

  • S.rstrip([chars]) -> string or unicode

    Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

    in your case the chars = ['[','e','d','i','t',']'] which contains 'd' there fore trailing string that formed by given chars is d[edit]

    try regular expression

    import re
    re.compile(r'\[edit\]$').sub('','Rhode Island[edit]')