Problem with keeping quotes
famous_person = "Dalai Lama disse:\n"
message = "\Se quer viver uma vida feliz, amarre-se a uma meta, não a pessoas nem a coisas\"
print(famous_person + message)
I've tried everything (including double quotes). If I put two quotes on the left gives error, if it is on the right I get no left quote... I'd like to keep both.
3 answers
To make your code cleaner, you can set the string with single quotes, so double quotes in the message will not interfere with the syntax:
texto = '"Mensagem entre aspas"'
Remembering that Python allows you to define the string in four ways: single quotes, double quotes, single quote trio and double quote trio (the last two for multi-line string). Regardless of which one to use, the other three will be considered as text within the string.
For quotation marks in a string you should use \
:
message = "\"Se quer viver uma vida feliz, amarre-se a uma meta, não a pessoas nem a coisas\""
The backslash (\
) serves to override the effect of a special language symbol within the string, leaving it only as a symbol.
By adding a third option, you can use the strings """ ... """
or ''' ... '''
to delimit the strings without the need to escape the quotes and apostrophes inside it:
>>> a = '''Disse ele: "era uma vez um gato xadrez" '''
>>> b = """e 'todos' ficaram "perplexos" com a afirmação."""
>>> print a + b
And the result: Disse ele: "era uma vez um gato xadrez" e 'todos' ficaram "perplexos" com a afirmação.