In Python, the backslash(\) is a special character. If you use the backslash in front of another character, it changes the meaning of that character.
Uses cases
Use the Python backslash (\) to escape other special characters in a string.
Example: if you have a string that has a single quote inside a single-quoted string like the following string, you need to use the backslash to escape the single quote character:
In Python, when you prefix a string with the letter r or R such as r'...' and R'...', that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes (\) as literal characters.
Raw strings are useful when you deal with strings that have many backslashes, for example directory paths on Windows.
Example:
s = "lang\tver\nPython\t3 print(s)"
Output:
Output:
lang ver
Python 3
However, raw strings treat the backslash (\) as a literal character. For example:
s = r"lang\tver\nPython\t3"print(s) #Output: lang\tver\nPython\t3
Convert a regular string into a raw string
To convert a regular string into a raw string, you use the built-in repr() function. For example:
s = '\n'raw_string = repr(s)print(raw_string) #Output: \n