Python String – Escape backslash

Python String – Escape backslash

To escape backslash character(s) inside a string in Python, you can use another backslash character before each of the backslash quote character inside the string.

In this tutorial, you shall learn how to escape a backslash character inside a string with examples.

1. Escaping backslash in string by using another backslash (\)

For example, consider the following program, where we need to have a string Hello \World.. There is a single backslash character inside the string which we need to escape using another backslash character.

Python Program

x = 'Hello \\World.'
print(x)
Run Code Copy

Output

Hello \World.

If you want two backslash characters in the string next to each other, then you write four backslash character, one for each of the two required backslash characters, making them four in total.

Python Program

x = 'Hello \\\\World.'
print(x)
Run Code Copy

Output

Hello \\World.

Summary

In this tutorial, we learned how to escape backslash characters inside a string in Python, with well detailed example programs.

Related Tutorials

Code copied to clipboard successfully 👍