How do I compare a value to a backslash?


Question

if (message.value[0] == "/" or message.value[0] == "\"):
    do stuff.

I'm sure it's a simple syntax error, but something is wrong with this if statement.

1
23
5/26/2018 4:37:17 PM

Accepted Answer

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

55
1/13/2010 6:32:47 PM

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon