Python Escape Characters
In Python, escape characters allow you to include special characters in a string that would otherwise be difficult or impossible to represent. An escape character is a backslash \ followed by a specific character that has a special meaning.
Example:
print(“Hello\nWorld”)
# Output:
# Hello
# World
Escape Character | Description | Example | Output |
---|---|---|---|
\\ | Backslash: If you want to print ‘\’ then we use \ | print(“This is a backslash: \\”) | This is a backslash: \ |
\n | Newline | print(“Hello\nWorld”) | Hello World |
\t | Tab | print(“Name\tAge”) | Name Age |
\b | Backspace | print(“Helloo\b”) | Hello |
\0 | Null Character | print(“Hello\0World”) | Hello World |
Raw String: A raw string is a string where escape sequences (like \n, \t, etc.) are treated as literal characters. You create a raw string by prefixing the string with r or R.
Example:
#without ‘r’ (Raw string)
print(”Hello\tWorld”)
#output: Hello World
#with ‘r’ (Raw string)
print(r”Hello\tWorld”)
#output: Hello\tWorld
Task
1. Write a Python program that prints the following text using escape sequences
Hello, it’s a beautiful day!
“Programming is fun,” she said.
2. Write a Python program that prints the file path C:\Program Files\MyApp using raw string.
3. Write a Python program that prints the following table using escape sequences the existing format is like this – NameAgeAlice30Bob25
Expected Output :
Name Age
Alice 30
Bob 25
4. Write a Python program that uses the backspace \b escape sequence to correct the following string from Helllo World to Hello World.
5. Write a Python program that inserts a null character \0 between two words (Hello\0World) and prints the string. For example, the string should be Hello World.
6. Write a Python program that prints the string Hello\nWorld exactly as it is, without interpreting the \n as a newline character using raw string.