Search code examples
pythonstrip

Why is it when I strip my string it takes out a character I need in python?


I am new to programming and I was trying to use python to help me with some data. For the most part, when I do a .rstrip('') it does what I want. There are a few times in which when I ask it to print the stripped version, I noticed it took off like an extra 'M' that I did not intend to take out. Am I doing something wrong?

An example of what I use is like this:

x = 'SomethingUnwanted_MO-WantedStuff'
f = x.rstrip('SomethingUnwanted_')
print f

What I would want in this case is 'MO-WantedStuff'. Every now and again however, when I hit print I will get O-WantedStuff. Am I doing something wrong?

Update: I realized I mistyped as was pointed out to me. I fixed that.


Solution

  • You seem to be confused as to what rstrip does:

    In [21]:
    
    x = 'SomethingUnwanted_MO-WantedStuff'
    f = x.rstrip('SomethingUnwanted_MO-WantedStuff')
    f
    Out[21]:
    ''
    

    vs:

    In [18]:
    
    x = 'SomethingUnwanted_MO-WantedStuff'
    f = x.split('_')[1]
    f
    Out[18]:
    'MO-WantedStuff'
    

    The docs:

    Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.

    EDIT

    Again you seem to be confused after your edit, from the above the passed in matching sequence is removed from the right side in your case nothing wil be removed:

    In [23]:
    
    x = 'SomethingUnwanted_MO-WantedStuff'
    f = x.rstrip('SomethingUnwanted_')
    f
    Out[23]:
    'SomethingUnwanted_MO-WantedStuff'
    

    You want strip if you want to strip the passed in match from the left side:

    In [24]:
    
    x = 'SomethingUnwanted_MO-WantedStuff'
    f = x.strip('SomethingUnwanted_')
    f
    Out[24]:
    'MO-WantedStuff'
    

    As shown by @chapelo if you're looking to just remove this string from any position then you can use replace:

    In [25]:
    
    x = 'SomethingUnwanted_MO-WantedStuff'
    f = x.replace('SomethingUnwanted_','')
    f
    Out[25]:
    'MO-WantedStuff'