Page 1 of 1

Python

Posted: 20 Oct 2018, 18:57
by Maj123
Hi,
I am studying for the test but I am confused about one of the special characters - "scape char" or \<char>. I googled it but I still do not understand their purpose and function.
Thank you

Re: Python

Posted: 21 Oct 2018, 11:24
by Mr. MacKenty
Hello!

Sometimes you might need to print the character " or maybe you need to print a new-line character. The problem comes when I try the following code:

Code: Select all

print(" "hello", said the stranger.")
Please try the code above, and watch it totally fail.

As you can see, the second " will cause python to think the print statement has ended. So we need a way to tell python to ignore a special character and just print it. We do this by ESCAPING it. Try the code below:

Code: Select all

print(" \"Hello\", said the stranger.")
Please understand the difference between the two code snippets. when I added a \ character, it basically told python to ignore the next character and treat it like a normal character (not the end of the print statement).

We escape characters when we want python to ignore them. We also use escape characters in other programming languages. If I wanted to add a line break, I could use \n. Give it a try below:

Code: Select all

print(" Hello weary traveller! \n Rest your feet and take refuge \n in our warm inn")
Please reply and let me know if this answers your question. Also, in the future, please post in our python forum. :-)

Re: Python

Posted: 21 Oct 2018, 13:19
by Maj123
Thank you! That answers my question.