Python String Escape Characters

python-excape-characters-ipcisco-1

In coding there are some special characters for every programming language. These special characters can be used with special chracters. In python coding there are also some special characters that are illegal in strings. To use these speical characters in strings we should use an additional character named python escape character. In this lesson, we will focus on this characters, python string escape character.

 

An escape character is backslash (\) that is followed by the special character that you would like to insert.

 

For example, using double quotes is prohibited in a python string. But with escape character, we can print this character. Let’s give the below example for this case.

 

 

msg = “One of the best movie series ever is “Lord of The Rings”. Is not it?”

 

The above python code will give an error. Because we use two double quotes in the string and we do not mentined this with escape characters.

 


You can also check How to Split Python Strings


 

Now, let’use escape character this time.

 

msg = "One of the best movie series ever is \"Lord of The Rings\". Is not it?"
print(msg)

 

The output of this message will belike below:

 

One of the best movie series ever is "Lord of The Rings". Is not it?

 

There are also other escape characters in python. Some of these escape characters are given below:

 

\\           Backslash

\b          Backspace         

\r           Carriage Return              

\f           Form Feed         

\xhh      Hex value

\n          New Line           

\ooo     Octal value       

\’            Single Quote    

\t           Tab       

 

Let’s do another example with another escape character. This time, we will use tab (/t) escape character.

 

character1 = "Legolas\t\tElf!"
character2 = "Gimli\t\tDwarf!"
print(character1)
print(character2) 

 

The output of this code will be like below:

 

Legolas                Elf!
Gimli                    Dwarf!

 

python-excape-characters-ipcisco-2

 


You can also learn How to Compare Python Strings


 

Let’s do a last example for single quote.

 

me = 'I\'am Gokhan.'
print(me)

 

The output of this python code will be like below:

 

I'am Gokhan.

excape-characters-in-python-ipcisco-1

We have talked about the python string escape characters and how to use special character by using an  escape character with them. You can create different python examples with differetn escape characters. By using these characters more, you can understand this lesson better. More practice makes this lesson more memorable for you.

 

Back to: Python Programming Course > Python Strings

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts