Introduction to Escape Sequences in Python
Escape sequences are a fundamental concept in Python programming, allowing you to work with characters that have special meanings or are otherwise challenging to include in strings. They are represented by a backslash(\) followed by a specific character and serve as a way to escape the usual interpretation of that character. Python’s escape sequences enable you to insert newline characters, tabs, quotes, and other special characters into strings without causing syntax errors. By using these sequences, it becomes convenient to add text to a new line (\n), add a single quote(\’) or double quotes(\”) within a string, etc. Let us understand by a simple string.
Example:
print("Hello \"EDUCBA\"!")
Output:
Explanation:
If we try to write”EDUCBA” with a double quote directly inside a string, it will raise a syntax error, we will use a backslash (\) before each double quote. By doing this, we can print EDUCBA within double quotes.
Table of contents
- Introduction
- List of Escape Sequences Available in Python
- When to use Escape Sequence in Python
- Difference between an escape single quotes and Double quotes in Python
- Different Ways of Printing Escape Characters in Python
- Advanced Techniques
- Common Pitfalls and Troubleshooting
- Best Practices and Tips
Key Takeaways
- Used to insert characters that cannot be inserted directly inside a string.
- Examples: \n for a Newline, \’ for a single quote, \” for a double quote, \t for a horizontal tab, \u for unicode, \b for backspace, \x for carriage return
- Use f-strings for complex strings.
- We can add special characters in our string with escape sequences
- Escape sequences allow us to print a string with single or double quotes as per our requirement
- We can print escape sequences with raw string or preceding escape sequences with backslash
List of Escape Sequences Available in Python
Sr. No. | Function | Name | Description |
1. | \’ | Single quote | Inserts a single quote inside a string |
2. | \” | Double quote | Inserts a double quote inside a string |
3. | \\ | Backslash | prints a backslash character |
4. | \n | Newline | Inserts a new line inside a string |
5. | \t | Horizontal Tab | Puts a tab space between text |
6. | \b | Backspace | Removes preceding space or character |
7. | \r | Carriage Return | Removes preceding content |
8. | \xhh | A character with hexadecimal value hh | Prints alphabets corresponding to hexadecimal value |
9. | \ooo | A character with octal value ooo. | Prints alphabets corresponding to the octal value |
When to use Escape Sequence in Python
We use escape sequences in Python to insert special characters or characters with special meaning, newlines, and tabs within a string. Let’s explore different escape sequences available in Python:
1. Single quote (\’): If we insert a single quote inside a string that is enclosed inside a pair of single quotes, then the compiler will print the syntax error for unexpected characters in the output to achieve the result with a single quote in a string we need to put a backslash (\) preceding to a single quote (\’). Let us understand with an example to print what’s up:
Code :
print('What\'s up')
Output:
Explanation: The above code prints a single quote before s in What’s up by using a backslash before that single quote, or it will result in an unintended error.
2. Double quote (\”): To print a word or sentence inside a double quote within a string or characters, we use (\”) before and after that specific word or sentence. Let’s understand with an example:
Code:
print("Hello \"World\"")
print("This is \"Escape sequence\" Example")
Output:
Explanation: The above code prints a World inside a double quote by adding a backslash before the double quotes.
3. Backslash (\\): To print a single backslash in a string, we use backslash two times inside our print statement as below:
Code:
print("Hello\\World")
print("Prints a backslash inside a string\\character")
Output:
Explanation: simply by adding two backslashes before any word or character, we can print a backslash in our result
4. Newline (\n): We cannot go to a new line by simply putting spaces in Python, to achieve this, we need to use a new line character within a string, for example, to print each fruit name on a newline we use an escape sequence as below:]
Code:
print("Apple\nKiwi\nGrapes\nFig")
Output:
Explanation: We can print every fruit name in a newline by writing an escape sequence for newline (\n).
5. Horizontal tab (\t): We can separate words within a string by using a tab space in between, which is equal to eight whitespaces. Let us understand with an example
Code:
print("Left\tRight")
print("Black\tWhite")
print("A\tTo\tZ")
Output:
Explanation: adding \t between words or characters separates them with eight white spaces, as shown in the output
6. Backspace (\b): Backspace moves the pointer to one preceding position, it erases a preceding space or character within a string
Code:
print("Hello!\bWorld")
print("ABCD \bEFGH")
Output:
Explanation: we can see from the above example that using \b after exclamation and space has removed them.
7. Carriage return (\r): A carriage return will move the cursor to the beginning of the line without advancing to a new line. It doesn’t necessarily overwrite characters; instead, it starts writing from the beginning of the line. Let’s see how it works:
Code:
print("Hello!\rWorld")
Output:
Explanation: In this example, the \r moves the cursor back to the beginning of the line after printing “Hello!”. Then, “World” is printed, starting from the beginning. Since “World” is shorter than “Hello!”, the remaining characters from the previous text (“lo!”) are not overwritten, resulting in “Worldlo!”.
8. Octal value: Octal value is an escape sequence in Python that has the octal representation of each character, so Python converts the octal value into a string. It is presented in ‘\ooo’ format, where ooo represents an octal value of characters.
Code:
print("\110\145\154\154\157")
Output:
Explanation: Each character of Hello is represented by its corresponding octal value preceding by a backslash
9. Hexadecimal value: ‘xhh’ is used to convert the hexadecimal value into a string in Python.
Code:
print("\x57\x6f\x72\x6c\x64")
Output:
Explanation: Each character of World is represented by its hexadecimal value preceding by an escape character \x
Difference between an escape single quotes and Double quotes in Python
Feature | Single Quote | Double Quotes |
Syntax | ‘Text’ | “Text” |
Enclosing Quotes | Wrap double quote amidst single quote to avoid backslash | Wrap single quote amidst double quote to avoid backslash |
Escaping quotes | ‘Isn’t it lovely’ | “Isn’t it lovely” |
Concatenating words | ‘Hello’ + ‘Sunshine’ | “Hello” + “Sunshine” |
Performance | Faster – Due to no scanning for variables and predetermined string length | Slower – Due to scanning for variables and checking length |
Application | Widely used in almost all programming languages | Mostly used in Python and PHP |
Different Ways of Printing Escape Characters in Python
There are three ways to print escape characters in Python:
1. repr() function
We can print escape characters in Python by using the repr() function before a string. This function does not resolve the escape sequences present in the string and returns the string in the same format as written inside a print statement in your Python program.
Code:
print(repr("Hello! \n This is \t repr() function"))
Output:
Explanation: In the example above, using the string inside a repr() function does not resolve the escape characters \n and \t as newline and tab. Instead, both escape characters will be printed precisely as written in the print statement.
2. Raw string notation (R/r)
We can initialize a string with raw string notation to print escape characters. Initializing a string with R or r triggers the repr() function to not resolve escape characters.
Code:
print(R"Hello! \n It will print esacpe characters: \t , \n")
print(r"1234\nABCD\tabcd")
Output:
Explanation: In this example, escape characters for tab and newline are printed as-is by initializing a string with R or r, as it triggers the repr() function not to resolve escape characters.
3. Double Backslash (\\)
We can print an escape sequence by concatenating a backslash before an escape sequence character.
Code:
print("Newline:\\n")
print("Tab:\\t")
print("Backspace:\\b")
Output:
Explanation: In this example, different escape sequences are printed by adding a backslash before each escape sequence.
Uses of Chr() and Ord()
When there is a need for an encryption and decryption process, chr() and ord(), functions come into play. Ord() function converts normal text into number format so that an unauthorized user can’t understand it, and chr() is used to get the normal text from the numerical format.
1) ord() Function
In Python, the ord() function is a built-in function that takes a character as a string argument and returns its integer ASCII value as output. It accepts only a single Unicode character as input.
Syntax:
ord(character_to_encode)
Example
Char_to_encode = 'F'
Encoded_value = ord(Char_to_encode)
print(f"Using ord(), The encoded value (ASCII value) for {Char_to_encode} is: {Encoded_value}")
Output:
Explanation: In this example, we want to convert the character ‘F’ into its ASCII value. We store the character in a variable and then use the ord() function with that variable as a parameter. Finally, we print the encoded value, which is 70 in this case.
2) chr() Function
In Python, the chr() function is a built-in function that takes an integer value as a string argument and returns its corresponding character. It accepts an integer number from a range between 0 and 1,114,111 only as input
Syntax:
chr(value_to_ decoded)
Example
Value_to_decode = 70
Decoded_value = chr(Value_to_decode)
print(f"Using chr(), The decoded value for {Value_to_decode} is: {Decoded_value} ")
Output:
Explanation: In this example, we want to convert the encoded number 70 back into its normal character format. We use the chr() function with the encoded value as a parameter and print the decoded character, which is ‘F’ in this case.
Advanced Techniques
Escape sequences are typically used for printing special characters within the string, here are some enhanced techniques that can be utilized while using escape sequences to improve readability while coding:
1. Printing escape characters: Python allows us to print literal characters by either using the repr() function or utilizing raw string notation (R or r).
Code:
print(repr("Hello\nWorld"))
print(R"Hii\nHow are you?")
print(r"Good\tmorning")
Output:
2. Octal and Hexadecimal Escape sequence: We can print characters with their octal and hexadecimal values using ASCII code for enhanced flexibility.
Code:
print("\110\145\154\154\157")
print("\x57\x6f\x72\x6c\x64")
Output:
3. Unicode Escape sequence: Print Unicode characters with their hexadecimal values using the\u or \U escape sequences. Below is an example of printing the symbol for Euro using Unicode with a hexadecimal value.e
Code:
print("\u20AC")
print("\U000020AC")
Output:
4. Formatting String: For enhanced readability, use the format() method for formatting complex strings.
Code:
name = "John"
print(f"Hii! {name}")
Output:
5. Conditional Escaping: Utilize escape sequences for conditional statements, as demonstrated below:
Code:
condition = True
escape_character = '\t' if condition else ' '
print(f"Before tab.{escape_character}After tab.")
Output:
Common Pitfalls and Troubleshooting
1. Problem with Backslash and Raw String: Be mindful while writing the path in your program; forgetting to add an extra backslash or writing a backslash two times within a raw string can lead to unexpected errors.
- Solution: To represent a single backslash (), use a double backslash (\) or a raw string (R or r) before initializing a string with a single backslash within a string.
2. Missing Backslash or Special Character: While using an escape sequence, one might forget to write a backslash before a special character or write a backslash after a special character, leading to unintended errors.
- Solution: Remember that a backslash precedes a special character and all special characters, resulting in a different output.
3. Octal and Hexadecimal Conflict: Mistakes might occur while using an octal (\ooo) and hexadecimal (\xhh) escape when representing characters.
- Solution: While using octal or hexadecimal values, carefully check which is the correct method for each escape sequence to avoid unexpected output.
4. Incompatibility with External Paths: Escape sequence interpretation may change for an external path or URLs.
- Solution: Use a raw string for external paths or network protocols.
5. Unaware of Triple-Quoted String: Not being aware of how a triple-quoted string handles single quotes or double quotes within a string.
- Solution: Triple-quoted strings preserve single and double quotes within a string and output the string the same as in a print statement with single and double quotes within a string.
Best Practices and Tips
- If a user needs to define the path or route of a particular file, note that the path itself includes backslashes. To include a backslash in the string, precede it with another backslash.
Example: F:\\Admin\\Host\\Files - Raw strings can be used to avoid unnecessary backslashes in paths.
Example: r”F:\Admin\Host\Files” - The use of escape sequences can decrease the clarity of a string, making it difficult for users to understand. Consider using f-strings to avoid an overabundant use of escape sequences.
- Test your code by printing the string to ensure that escape sequences are properly used and have not become part of the string.
- While writing regular expressions (REGEX), avoid using escape sequences. Instead, make use of raw strings.
Conclusion
Escape sequences provide users with immense control over string manipulation. They enable the addition of text to new lines, insertion of quotes, and more. Additionally, escape sequences ease the work by offering advanced techniques to customize the code according to specific needs.
FAQs
Q1. While calculating the length of the string, does the length function include sequence characters?
Answer: Although special characters are not part of the string in the final output, the length function does include them when calculating the length.
Q2. Is there any range of digits and characters specified for octal and hexadecimal escapes?
Answer: The range for octal escapes starts from 0 and goes up to 7. For hexadecimal escapes, the range is from 0 to 9 and from A to F (both lowercase and uppercase).
Q3. What is the meaning of the term “Custom Escape mechanism”?
Answer: The default escape sequence doesn’t handle all conditions as per user needs. Hence, the escape sequence can be customized. This process is called a Custom Escape mechanism.
Techniques for Custom Escape Mechanism:
- REGEX (Regular Expressions): Regular expressions are expressions or equations consisting of letters, numbers, characters, and symbols defined to solve custom problems.
- Mapping Dictionary: This method works by using a key-value pair. Each key has a value, and by using those keys in the string, one can print the corresponding value in the output.
Recommended Articles
We hope this EDUCBA information on “Escape Sequences in Python” benefited you. You can view EDUCBA’s recommended articles for more information.