4
votes

I have a function that begins like this:

def solve_eq(string1):
    string1.strip(' ')
    return string1

I'm inputting the string '1 + 2 * 3 ** 4' but the return statement is not stripping the spaces at all and I can't figure out why. I've even tried .replace() with no luck.

3
Strings are immutable so don't expect anything to act on them in-place. Use the return value of string1.strip(). - Andras Deak
I need to further modify the string, so could I do something like string2 = string1.strip (' ') ? - Lanier Freeman
Try it. (That was exactly my point). You can also rebind string1 = string1.strip(' '). - Andras Deak
Sweet, thanks so much! - Lanier Freeman
strip will not do what you want. strip removes trailing and leading whitespace. This is simply a matter of string immutability and using string1.replace(' ', '') to solve this problem. - idjaw

3 Answers

14
votes

Strip does not remove whitespace everywhere, only at the beginning and end. Try this:

def solve_eq(string1):
    return string1.replace(' ','')

Using strip() in this case is redundant (obviously, thanks commentators!).

P.s. Bonus helpful snippet before I take my SO break (thanks OP!):

import re
a_string = re.sub(' +', ' ', a_string).strip()
7
votes

Strip doesn't change the original string since strings are immutable. You should set a return value to the stripped string or just return the stripped string.

Option 1

def solve_eq(string1):
    string1 = string1.replace(' ', '')
    return string1

Option 2

def solve_eq(string1):
    return string1.replace(' ', '')

edit: instead of string1.strip(' '), use string1.replace(' ', '')

1
votes

strip returns the stripped string; it does not modify the original string.