Check if a string contains a Backslash `\` in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Check if a string contains a Backslash \ in Python #

Use the in operator to check if a string contains a backslash, e.g. if '\\' in my_str:. Backslash characters have a special meaning in Python, so they have to be escaped with a second backslash.

main.py
my_str = 'bobby\\hadz' print(my_str) # 👉️ bobby\hadz if '\\' in my_str: print('The string contains a backslash') else: print('The string does NOT contain any backslashes') print('\\' in my_str) # 👉️ True
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 backslash \ as a literal character.

main.py
file_name = 'C:\\Users\\Bob\\Desktop\\employees.csv' # 👇️ C:\Users\Bob\Desktop\employees.csv print(file_name)

We used the in operator to check if the string contains a backslash.

main.py
my_str = 'bobby\\hadz' print(my_str) # 👉️ bobby\hadz if '\\' in my_str: print('The string contains a backslash') else: print('The string does NOT contain any backslashes') print('\\' in my_str) # 👉️ True

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

If you need to check if a string contains 2 backslashes next to one another, make sure to escape each backslash character.

main.py
my_str = 'bobby\\\\hadz' print(my_str) # 👉️ bobby\\hadz print('\\\\' in my_str) # 👉️ True

We used 4 backslashes to check if the string contains 2 backslash characters next to one another.

You can also prefix a string with r to mark it as a raw string.

main.py
my_str = r'bobby\hadz' print(my_str) # 👉️ bobby\hadz print('\\' in my_str) # 👉️ True
Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

However, we can't mark a string containing a single backslash as a raw string because the backslash escapes the quote and causes an error.

Even in raw strings, backslash characters can be used to escape quotes.

main.py
print(r'\\') # 👉️ \\ print(r'\'') # 👉️ \' # ⛔️ SyntaxError: unterminated string literal (detected at line 7) print(r'\')

There is no way to define a raw string that only contains a backlash.

The backslash in the last line escapes the quote and causes a SyntaxError.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.