tags:

views:

574

answers:

3

Hi. Here is some code:

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

I'm sure it's a simple syntax error, but something is wrong with my if statement. Any ideas to help out a python newbie?

Cheers

+16  A: 

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.

Adam Bernier
The parentheses are valid, but meaningless.
Adam Crossland
+1  A: 

Try like this:

if message.value[0] == "/" or message.value[0] == "\\":
  do_stuff
gruszczy
+16  A: 

when you check for equality, you can also simply do this:

if message.value[0] in ( '/', '\\' ):
    do_stuff
poke
Succinct and Pythonic.
Adam Crossland
Or just `message.value[0] in "/\\":` because strings are iterable.
Chris Lutz
If you can be certain that `message.value[0]` is a string of length 1 (yes, I know, I know...).
Ignacio Vazquez-Abrams
message.value[0] in "/\\ can be dangerous - too easy to screw up during maintenance 2 weeks later, or by another programmer.
Hamish Grubijan
If you wanted to allow for `message` being an empty string, the idiom would be `if message.value[:1] in ('/', '\\')`.
bobince
This is more of a comment than a valid answer...
abyx
Don't forget that EIBTI
Jason w