Escape sequencing
Escape Sequencing in Python
When printing strings containing single or double quotes, Python may raise a SyntaxError if the same type of quote is used to define the string. To handle this, you can use triple quotes (''' or """) or escape sequences. Escape sequences begin with a backslash (\) and allow special characters to be included in strings. If a string is defined with single quotes, any single quotes inside it must be escaped, and the same applies for double quotes.
Example:
# Using triple quotes
str1 = '''She said, "Let's code!"'''
print("String with triple quotes:")
print(str1)
# Escaping single quotes
str2 = 'It\'s a sunny day!'
print("\nEscaping single quotes:")
print(str2)
# Escaping double quotes
str3 = "He shouted \"Hello!\" loudly."
print("\nEscaping double quotes:")
print(str3)
# Escaping backslashes for file paths
str4 = "D:\\Projects\\Python\\"
print("\nEscaping backslashes:")
print(str4)
# Using tab escape sequence
str5 = "Hello\tWorld"
print("\nTab:")
print(str5)
# Using new line escape sequence
str6 = "Line1\nLine2"
print("\nNew Line:")
print(str6)Output:
String with triple quotes:
She said, "Let's code!"
Escaping single quotes:
It's a sunny day!
Escaping double quotes:
He shouted "Hello!" loudly.
Escaping backslashes:
D:\Projects\Python\
Tab:
Hello World
New Line:
Line1
Line2