Francesco Tattoli Francesco Tattoli - 5 months ago 8
Python Question

pycharm exercise "Character Escaping": task completed but wrong syntax

I'm following the built-in tutorial in PyCharm Edu Edition and I'm stuck on Strings - Character Escaping.
In the exercise I'm asked to print the following:
The name of this ice-cream is "Sweeet'n'Tasty"
by using character escaping, and here's my code:

print("The name of this ice-cream is \"Sweeet\'n\'Tasty\"")


and it still gives me "Sorry the wrong string is printed". Honestly I don't think I printed a wrong string. Any help?

Answer

You have to escape " because you use it in your print but your ' does not need to be protected.

Printing "\'n" and "'n" will output the same line but the escape, even if not visible, will generate something that is read by your exercise controller.

Try removing the \ before the '

print("The name of this ice-cream is \"Sweeet'n'Tasty\"")

Another solution for string containing " or ' is to use triple " like this:

print("""The name of this ice-cream is "Sweeet'n'Tasty\"""")

In this very case, the fact that the sentence is terminated by a " force to protect it again, but the " in the middle does not need to be protected.

You can also invert the use of ' and " to protect the ' or the "

print('The name of this ice-cream is "Sweeet\'n\'Tasty"')

And use of 3 ' is possible too:

print('''The name of this ice-cream is "Sweeet'n'Tasty"''')

If that still don't work, could you provide the assert test ?

Edit:

This seems to be the issue you are facing: http://iswwwup.com/t/d08b1b05234e/print-out-text-using-one-string-in-python.html

Comes from an ambigous test requirement / IDE behaviour.