Monday 20 September 2021

Escape special characters in python

Python has many special characters like \n, \t, \b, \r etc., In this post, I am going to explain two solutions to escape these special character in a string and print as it is.

 

Solution 1: By escaping special characters.

str1 = "Hi, I am escaping \\n and also \\t"

Solution 2: Prefixing the string with ‘r’.

str2 = r"Hi, I am escaping \n and also \t"


escape_special_chars.py

str1 = "Hi, I am escaping \\n and also \\t"
str2 = r"Hi, I am escaping \n and also \t"

print('str1', ' -> ' , str1)
print('str2', ' -> ' , str2)


Output

str1  ->  Hi, I am escaping \n and also \t
str2  ->  Hi, I am escaping \n and also \t


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment