简体   繁体   中英

How to prevent closing of " in variable

I have a variable

sentence = "In 1794, shortly after his arrival in Manchester, Dalton was elected a member of the Manchester Literary and Philosophical Society, the "Lit & Phil", and a few weeks later he communicated his first paper on "Extraordinary facts relating to the vision of colours", in which he postulated that shortage in colour perception was caused by discoloration of the liquid medium of the eyeball. In fact, a shortage of colour perception in some people had not even been formally described or officially noticed until Dalton wrote about his own. Since both he and his brother were colour blind, he recognized that this condition must be hereditary."

Now this may have both "" and '' due to which it will close the value of the variable. I want to prevent this. Is there any other way of storing a string?

Escape the embedded quotes with \\ :

"Some text with \"embedded\" quotes"

If your text contains only double quotes, you can single quotes and not have to escape the double quotes:

'Some text with "embedded" quotes'

Last but not least, you can triple the outer quotes and save yourself having to escape newlines too:

"""Some text with "embedded" quotes"""
"""Some text with "embedded" quotes
and a newline too"""

For your example, single quotes would already do the trick:

sentence = 'In 1794, shortly after his arrival in Manchester, Dalton was elected a member of the Manchester Literary and Philosophical Society, the "Lit & Phil", and a few weeks later he communicated his first paper on "Extraordinary facts relating to the vision of colours", in which he postulated that shortage in colour perception was caused by discoloration of the liquid medium of the eyeball. In fact, a shortage of colour perception in some people had not even been formally described or officially noticed until Dalton wrote about his own. Since both he and his brother were colour blind, he recognized that this condition must be hereditary.'
a="""triple quoted strings can contain quote like this " without ending the string"""

您可以使用三引号,例如:

sentence = """ long sentence with all 'kind" of symbols """

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM