Lanier Freeman Lanier Freeman - 1 year ago 140
Python Question

Python .strip method not working

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.

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download