[Tutor] Trouble Removing Whitespace
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Nov 7 04:09:08 EST 2016
On 07/11/16 03:25, Jason Durnen wrote:
> This is the code that I type in, but the result will not trim the extra
> space.
The tricky thing about white space is that you can't se it, so how do
you know it is there or not? One way is to surround it with something
you can see:
data = 'a string '
print(':'+data+':') # -> :a string :
data = data.rstrip()
print(':'+data+':') # -> :a string:
> The first group is how it is shown in the book, but when it prints,
> the ' is not included anywhere.
Correct that's because the quote is what tells Python
that it is a string. When the string is printed Python
does not show the quotes. You can tell Python to include
the quotes by asking it to print the *representation*
of the data using the repr() function:
print(repr(data))
This is another way of seeing the whitespace.
> In this section, I added double quotations around the single quotation and
> the word python, however I can't get it to remove the whitespace when it
> print the word. Is there something that I'm missing?
The problem is that rstrip() only strips whitespace as far back
as the first non-white-space character. In your case that's
the ' so rstrip() can find no whitespace to remove.
Try your original code again but use either of the techniques
I mentioned to see the whitespace. I think you'll find that
it was removed after all.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list