Concatenate a string with a backslash in Python


Borislav Hadzhiev

Mon Jun 20 20222 min read


Photo by Oleg Ivanov

Concatenate a string with a backslash in Python #

Use a second backslash to concatenate a string with a backslash in Python, e.g. result_1 = 'one\\' + 'two'. The backslash \ character has a special meaning, so it has to be escaped with a second backslash.
result_1 = 'one\\' + 'two' print(result_1) # 👉️ 'one\two' result_2 = r'one\two' print(result_2) # 👉️ 'one\two' first = 'one' second = 'two' result_3 = rf'{first}\{second}' print(result_3) # 👉️ 'one\two'

The first example uses a second backslash to escape a backslash character.

The backslash \ character has a special meaning in Python - it is used as an escape character (e.g. \n or \t).

By adding a second backslash, we treat the \ as a literal character.
file_name = 'C:\\Users\\Bob\\Desktop\\employees.csv' # 👇️ C:\Users\Bob\Desktop\employees.csv print(file_name)

Similarly, if you need to have 2 backslashes next to one another, you would have to use 4 backslashes.
result_1 = 'one\\\\' + 'two' print(result_1) # 👉️ 'one\\two'

An alternative solution is to prefix the string literal with r to mark it as a raw string.
file_name = r'C:\Users\Bob\Desktop\employees.csv' # 👇️ C:\Users\Bob\Desktop\employees.csv print(file_name)
Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

If you are constructing a path, e.g. to a directory or a to a file, you can use forward slashes instead of backslashes.
file_name = 'C:/Users/Bob/Desktop/employees.csv' # 👇️ C:/Users/Bob/Desktop/employees.csv print(file_name)

A forward slash can be used in the place of a backslash when you need to specify a path.

You can also use a raw, formatted-string literal to treat a backslash as a literal character.
first = 'one' second = 'two' result_3 = rf'{first}\{second}\three' print(result_3) # 👉️ 'one\two\three'

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

By prefixing the string with r as well as f, we mark it as both - a raw string and a formatted-string literal.

Since backslash characters have a special meaning in Python, we need to treat them as a literal character by:

  • escaping each backslash with a second backslash
  • prefixing the string with r to mark it as a raw string
  • using forward slashes in the place of backslashes in the path
Use the search field on my Home Page to filter through my more than 1,000 articles.