How to store a string containing both single quote

2019-08-12 03:05发布

问题:

(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How's it going?) 

I want to store this sms message in python as a string. How can I do this?

回答1:

Triple quotes - this will allow embedded single and double-quotes without escape characters.

s = """(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How's it going?)"""


回答2:

Backslash escaping is the quick answer:

>>> '(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How\'s it going?)'
'(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How\'s it going?)'
>>> a = '(+CMGL: 2,"REC READ","DD-Etopup",,"11/11/04,12:48:51+22" Hye! How\'s it going?)'
>>> a.split(',')
['(+CMGL: 2', '"REC READ"', '"DD-Etopup"', '', '"11/11/04', '12:48:51+22" Hye! How\'s it going?)']
>>> a.split(',')[5]
'12:48:51+22" Hye! How\'s it going?)'
>>> len(a.split(',')[5])
34