[Tutor] Uses for backslashes

Alan Gauld alan.gauld at yahoo.co.uk
Sun Jun 25 04:02:35 EDT 2023


On 25/06/2023 08:05, Jack Simpson wrote:

> following character i.e. \n is a line feed, \t is a new tab but I can"t
> find why it is used in a case like this. Thanks for your help.
> 
> var1 = "my computer" >= "my chair"
> 
> print("Is \"my computer\" greater than or equal to \"my chair\"? Result: "
> , var1)

This is called escaping a character. It tells Python to treat the next
character as a literal character and ignore its special meaning. ie. it
prints the quote sign rather that treating it as the end of the string.

Without the quotes Python would see:

A short string:           "Is "
two unquoted words:       my computer
Another short string:     " greater than or equal to "
Another two words:        my chair
Another short string      "? Result: "

The unquoted words make no sense to Python so in reality
you'd get an error, hence the need for the \" notation.

However, this is very unusual practice in Python. Because Python has
multiple ways of quoting strings it's far more common to surround the
outer string with a different quote sign:

'Is "my computer" greater than or equal to "my chair"? Result: '

By using single quotes to define the string limits we are free
to use double quotes inside. And if the string contains both
double and single quotes(an apostrophe say) then we can surround
the string with triple quotes:

'''I'd like to teach the world to sing "Amazing Grace"'''

Your tutorial is technically correct in showing that use
of \ but in practice it is only occasionally seen. Mostly
in something called a regular expression which you probably
haven't covered yet.

-- 
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