Why Doesn't .strip() Remove Whitespaces?
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
Solution 1:
strip
does not remove whitespace everywhere, only at the beginning and end. Try this:
def solve_eq(string1):
return string1.replace(' ', '')
This can also be achieved using regex:
importrea_string= re.sub(' +', '', a_string)
Solution 2:
strip
doesn't change the original string since strings are immutable. Also, instead of string1.strip(' ')
, use string1.replace(' ', '')
and set a return value to the new string or just return it.
Option 1:
def solve_eq(string1):
string1 = string1.replace(' ', '')
return string1
Option 2:
def solve_eq(string1):
return string1.replace(' ', '')
Solution 3:
strip
returns the stripped string; it does not modify the original string.
Post a Comment for "Why Doesn't .strip() Remove Whitespaces?"