[Tutor] String method "strip()" not working
Dave Angel
davea at davea.name
Sat Mar 7 16:07:24 CET 2015
On 03/07/2015 08:15 AM, Akash Shekhar wrote:
> I am trying to learn how to use strip() method. It is supposed to cut out
> all the whitespace as I read in the tutorial. But the code is not working.
>
> Here's my code:
>
> sentence = "Hello, how are you?"
>>
>>
>>> print(sentence)
>>
>>
>>> print(sentence.strip())
>>
>>
>>> input("\n\nPress enter key to exit.")
>>
>>
>>
> Here's it's output:
>
> Hello, how are you?
>> Hello, how are you?
>>
>> Press enter key to exit.
>>
>
>
> Both results are same.
>
> P.S.: I am using Python 3.1 IDLE on Windows 7.
Thanks for mentioning the python version and OS.
You don't have any whitespace at the beginning nor end of the string
bound to sentence. So there's nothing to strip. By the way, if you're
checking such a function, it's sometimes more informative to write
print(repr(sentence))
which will add quotes at begin and end, and show newlines and tabs as
escape sequences.
If you only want to strip from one end of the string, you'd use lstrip()
or rstrip().
If you're also trying to remove characters from the middle of the
string, you might use translate() or the string method replace(). For
example, to remove all spaces from a string, use
sentence.replace(" ", "")
--
DaveA
More information about the Tutor
mailing list