7

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Lanier Freeman
  • 273
  • 2
  • 3
  • 6

3 Answers3

22

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)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Eugene
  • 1,539
  • 12
  • 20
  • 3
    I'm one of the downvoters. Don't take this personally, and most certainly don't give up on SO. The reason I downvoted the answer is that OP has a very fundamental misconception of how strings and related methods work. The main issue is not using the return value of `.strip()`, but rather thinking that the method mutates the input string. Questions like this pop up like mushrooms, and are essentially typo questions (not actual typos, but brain farts). Answering such questions will stop automatic deletion processes to kick in once the question is closed. You're wasting your time answering them. – Andras Deak -- Слава Україні Nov 06 '16 at 00:51
  • 2
    I'm a robot, I never take things personally... Yeah, "I've even tried `.replace()`" kinda gives it away. But downvoting as opposed to a request to delete in the comments? I'm only in it for the points ;) You're totally right though, questions need to be filtered, or at least immediately tagged based on points or something. The large majority of the questions I answer, I do so using SO! Maybe SO should make available a JFGI flag for noobs? Ha! Anyway, thanks for the explanation, appreciate it. – Eugene Nov 06 '16 at 01:02
9

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(' ', '')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Marissa Novak
  • 544
  • 3
  • 6
2

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

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101