Index

  1. Intro
  2. Uses cases
  3. Backslash in F-strings
  4. Raw Strings

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:
s = '"Python\'s awesome" She said'

Backslash in F-strings

Warning

that an f-string cannot contain a backslash character as a part of the expression inside the curly braces {}.

colors = ['red','green','blue'] 
s = f'The RGB colors are:\n {'\n'.join(colors)}' print(s)

Output:

SyntaxError: f-string expression part cannot include a backslash

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 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

Link to original


Link to original