Index
Intro
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:
- it’s used in the Python Escaping Sequences to ad more functionality to the Python Strings.
Backslash in F-strings
Warning
that an f-string cannot contain a backslash character as a part of the expression inside the curly braces
{}
.
Output:
Raw Strings
raw-string
Python Raw String
read: Python Backslash (escaping character) and Python Escaping Sequences
Definition
In Python, when you prefix a string with the letter
r
orR
such asr'...'
andR'...'
, 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:
Output:
Output: lang ver Python 3
However, raw strings treat the backslash (
\
) as a literal character. For example:
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:
Link to original
Link to original