In Python, escape characters are sequences starting with a backslash (\) that represent special characters within strings. They are useful for including symbols or formatting that cannot be typed directly inside a string.

Common Escape Characters

Below are some of the most common escape characters in Python and their functions:

  • \n: New line (line break)

  • \t: Horizontal tab

  • \\: Literal backslash (\)

  • \': Literal single quote (')

  • \": Literal double quote (")

  • \r: Carriage return

  • \b: Backspace (deletes the previous character)

  • \f: Form feed

  • \v: Vertical tab

  • \ooo: Represents a character by its octal value, where ooo is an octal number

Practical Examples

Here are some examples of how these escape characters are used in Python:

print("First line\nSecond line")  # New line
print("Column 1\tColumn 2\tColumn 3")  # Tabulation
print("Path: C:\\Users\\John")  # Backslash
print("He said: \"Python is amazing!\"")  # Double quotes
print("This will be deleted\b!")  # Backspace

Expected output:

First line
Second line
Column 1	Column 2	Column 3
Path: C:\Users\John
He said: "Python is amazing!"
This will be deleted!

Escape Characters and Raw Strings

If you want to prevent escape characters from being interpreted, you can use a raw string by prefixing the string with r:

print(r"C:\Users\John")  # Displays exactly "C:\Users\John" without processing backslashes

This is especially useful for file paths in Windows, where backslashes are common.

Conclusion

Escape characters are essential for correctly formatting strings in Python. They allow you to include spacing, line breaks, and special symbols without syntax errors. Understanding their use can help you manipulate strings more effectively in your code.

Now that you know about escape characters in Python, try using them to enhance your output formatting! 🚀

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/escape-characters-in-python/