Dev ❤ Ops

Escape Character in Python

In Python, the backslash (“\”) character is used as an escape character to indicate that the character following it should be treated specially. For example, the backslash can be used to insert a new line or a tab character into a string.

Here are some examples of using the backslash as an escape character:

  • \n: Inserts a newline character
  • \t: Inserts a tab character
  • \\: Inserts a backslash character
  • \’: Inserts a single quote character
  • \”: Inserts a double quote character

Here’s an example of how you can use the backslash to insert a newline character into a string:

string = "This is a string\nwith a newline character"
print(string)

Output:

This is a string
with a newline character

You can also use triple quotes (”’ or “””) to define a string that spans multiple lines, without having to use the backslash escape character. For example:

string = """
This is a string
with multiple lines
"""
print(string)

Output:

This is a string
with multiple lines

Note that you can use the backslash to escape the triple quotes if you need to use triple quotes within the string. For example:

string = """This string has "triple quotes" within it"""
print(string)

string = "This string has \"triple quotes\" within it"
print(string)

Output:

This string has "triple quotes" within it
This string has "triple quotes" within it

This article is created based on experience but If you discover any corrections or enhancements, please write a comment in the comment section or email us at contribute@devopsforu.com. You can also reach out to us from Contact-Us Page.

For more information please visit python.org

Follow us on LinkedIn for updates!

Leave a comment

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