Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't .strip() remove whitespaces? [duplicate]

Tags:

python

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.

like image 463
Lanier Freeman Avatar asked Nov 27 '22 20:11

Lanier Freeman


2 Answers

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:

import re

a_string = re.sub(' +', '', a_string)
like image 103
Eugene Avatar answered Dec 10 '22 12:12

Eugene


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(' ', '')
like image 38
Marissa Novak Avatar answered Dec 10 '22 12:12

Marissa Novak