-3

how can I remove whitespaces from within a user input string? Can't I use .replace(" ","")? it didn't work for me.
My code:

>>>p=raw_input ("Enter phrase:\n")    
>>>p.replace(" "."")

It still outputs user input phrase WITH spaces..what am I doing wrong?Please help.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Maria chalsev
  • 53
  • 1
  • 2
  • 5
  • 5
    1. It is a `,` (comma) and not a `.` (period) that separates the arguments to the function 2. `str.replace` is not inplace. You need to assign it back – Bhargav Rao May 21 '15 at 17:11
  • Possible duplicate of http://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out – Bhargav Rao May 21 '15 at 17:15
  • My bad, i had a comma in my code. Still didn't work. – Maria chalsev May 21 '15 at 17:27

2 Answers2

8

since strings are immutable in python, str.replace returns a new string, it does not modify the existing string

p = p.replace(" ","")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
3

You can use replace, but you have to assign its return to the variable

>>>p=raw_input ("Enter phrase:\n")

>>>p=p.replace(" ","")
rafaelc
  • 57,686
  • 15
  • 58
  • 82