TrigonDark
TrigonDark

Reputation: 194

Incorrect syntax with a string that takes up more than 1 line Python

I'm trying to create a program that assigns whatever the person types in response to a certain prompt, it takes up more than two lines and I'm afraid that it's not recognizing the string because it is on separate lines. It keeps popping up with an "Incorrect Syntax" error and keeps pointing to the line below. Any way I can fix this?

given = raw_input("Is " + str(ans) + " your number?
Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate that I guessed correctly")

Upvotes: 2

Views: 175

Answers (4)

Henry Keiter
Henry Keiter

Reputation: 17168

You need to use multi-line strings, or else parentheses, to wrap a string in Python source code. Since your string is already within parentheses, I'd use that fact. The interpreter will automatically join strings together if they appear next to each other within parens, so you can rewrite your code like this:

given = raw_input("Is " + str(ans) + " your number?"
                  "Enter 'h' to indicate the guess is too high. "
                  "Enter 'l'to indicate the guess is too low. "
                  "Enter 'b' to indicate that I guessed correctly")

This is treated much as though there was a + between each of those strings. You could also write the plusses in yourself, but it's not necessary.

And as I alluded to above, you could also do it with triple-quoted strings (''' or """). But this (in my opinion) basically makes your code look awful, because of the indentation and newlines it imposes--I much prefer sticking with parentheses.

Upvotes: 6

2rs2ts
2rs2ts

Reputation: 11026

I would use multi-line strings, but you also have the following option:

>>> print "Hello world, how are you? \
... Foo bar!"
Hello world, how are you? Foo bar!

A backslash tells the interpreter to treat the following line as a continuation of the previous one. If you care how your code blocks look, you could append with +:

>>> print "Hello world, how are you? " + \
...       "Foo bar!"
Hello world, how are you? Foo bar!

Edit: as @moooeeeep stated, this escapes the newline character at the end of the statement. If you have any whitespace afterward, it'll screw everything up. So, I leave this answer up for reference only - I didn't know it worked as it does.

Upvotes: 1

moooeeeep
moooeeeep

Reputation: 32502

Just use a multiline string. This way newlines in the string literal will be preserved (I assume this is what you want to achieve).

Example:

given = raw_input("""Is %s your number?
Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate that I guessed correctly""" % ans)

Upvotes: 0

James Thiele
James Thiele

Reputation: 413

You could also do triple quoted strings. The begin and end with """ and can span multiple lines.

Upvotes: -1

Related Questions