Learning Coding
Learning Coding

Reputation: 9

Python String - need to print an string with double quote at end

I need to print the statement - He said - "I'am not coming today" but when it is enclosed in three double quotes as below -

print("""He said - "I'am not coming today"""")

error is thrown - SyntaxError: EOL while scanning string literal

While if use

print("""He said - "I'am not coming today\"""")

it is printed.

Please help me to understand what is wrong in first print.

Upvotes: 1

Views: 601

Answers (2)

hygull
hygull

Reputation: 8740

The thing is, """ pair is basically used to create multi-line string. So, adding 1 more " and use """" goes beyond the syntax and that is why we need to escape it using \" to make " as part of the string at end. While placing it in middle is okay.

Wrong

>>> print("""He said - "I'am not coming today"""")
  File "<stdin>", line 1
    print("""He said - "I'am not coming today"""")
                                                 ^
SyntaxError: EOL while scanning string literal
>>>

Correct (using \" is correct choice to make " as part of string at end)

>>> print("""He said - "I'am not coming today\"""")
He said - "I'am not coming today"
>>> 

Note 1: In case of using " to surround string, \" is mandatory to make " as part of the string wherever it may be.

>>> print("He said - \"I'am not coming today\"")
He said - "I'am not coming today"
>>>

Note 2: But in case of using ' it is not required (Here you will need to use \' to make ' as part of string).

>>> print('He said - "I\'am not coming today"')
He said - "I'am not coming today"
>>> 

Upvotes: 0

You should not be using """ for this.

print("He said - \"I\'am not coming today\"")

You need to escape (\) the quotes so python knows you want the literal quote marks.

Note, since you use " you do not need to escape the ' but it is good practice.

Upvotes: 1

Related Questions