Python

This forum is a place to ask questions about the python programming language.
Post Reply
User avatar
Maj123
Helper!
Posts: 9
Joined: 17 Sep 2018, 10:14

Python

Post by Maj123 » 20 Oct 2018, 18:57

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

Tags:

User avatar
Mr. MacKenty
Site Admin
Posts: 88
Joined: 28 Apr 2018, 17:06
Answers: 3

Re: Python

Post by Mr. MacKenty » 21 Oct 2018, 11:24

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. :-)
1 x

User avatar
Maj123
Helper!
Posts: 9
Joined: 17 Sep 2018, 10:14

Re: Python

Post by Maj123 » 21 Oct 2018, 13:19

Thank you! That answers my question.
1 x

Post Reply