By Lenin Mishra
If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.
Escape Sequences in Python
Escape sequences or Escape characters in Python, are used to insert characters that are illegal in a string.
Here is an example of an illegal character in a Python string.
Example1 - "Pylenin said, "Hi there"" Example2 - 'Pylenin said, 'Hi there''
In Example 1, we have double quotes inside double quotes. In Example 2, we have single quotes inside of single quotes. These qualify as illegal characters in a string.
If we try to print it, Python will throw us a
One way to fix this is by using Escape characters or sequences.
If we are using single quotes to represent a string, all the single quotes inside the string must be escaped with a
Similarly, if we are using double quotes to represent a string, all the double quotes inside the string must be escaped with a
\ character. .
str1 = "Pylenin said, \"Hi there\"" print(str1) str2 = 'Pylenin said, \'Hi there\'' print(str2)
Pylenin said, "Hi there" Pylenin said, 'Hi there'
Other Escape Sequences in Python
|\newline||Backslash and newline ignored|
|\r||ASCII Carriage Return|
|\t||ASCII Horizontal Tab|
|\v||ASCII Vertical Tab|
|\ooo||Character with octal value ooo|
|\xHH||Character with hexadecimal value HH|
- How to create a string in Python?
- How to access characters in a Python string?
- How to replace characters in a string in Python?
- How to concatenate strings in Python?
- How to iterate through a string in Python?
- Check if a Substring is Present in a Given String in Python
- Python String Formatting - The Definitive Guide
- Commonly used Python string methods