How to Use Escape Characters in Python 


               


How to Use Escape Characters in Python



Python


In this article, we show how to use escape characters in Python.

An escape character lets you use characters that are otherwise impossible to put into a string.

An escape character consists of a backslash (\) followed by the character you want to add to the string.

There are several different different escape characters.

The table below shows these escape characters.
Escape Character Prints as
\' Single quote
\" Double quote
\t Tab
\n Newline (line break)


So above is the table of escape characters in Python.

If you are using single quotes to print out a string and you have a single quote in the string, then you would have either 1 of 2 choices: you can use double quotes to enclose the string or you can use the escape character within the string enclosed by single quotes to have a single quote appear in the string.

If you are using double quotes to print out a string and you have a double quote within the string, then you could either use single quotes to enclose the string or use the double quote escape character within the string.

If you need a tab (8 spaces) to appear in a string, then you would put a tab (\t) escape character at the beginning of the string.

If you want a newline (line break) to appear within a string, then you would just place a newline escape character (\n) where you would a newline (line break).

So let's actually run through some Python code to see these escape characters in action.



So the first string we have is one in which we use the single quote escape character. Since we enclose the entire string in single quotes, if we want to put a single quote within the string, we must use a single quote escape character (\').

In the second string, we use double quotes to enclose the string. So to put double quotes within the string, we must use a double quote escape character (\"). We use two of these in the above string.

In the third string, we want to insert a tab into the string. In Python, a tab inserts 8 spaces into the string. To add a tab into a string, we use the tab escape character (\t) in the string. You can see that in the output string, there is 8 spaces at the beginning.

Lastly, we want to insert a line break into a string. We insert 2 line breaks in the above string with the newline escape character (\n).

And this is how to use escape characters in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...