Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Having both single and double quotation in a Python string

I'm trying to have a string that contains both single and double quotation in Python (' and "). However, Python always automatically corrects this to (', "). I wonder if there's a way to put a double quotation and a single quotation together as it is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use triple quotes.

"""Trip'le qu"oted"""

or

'''Ag'ain qu"oted'''

Keep in mind that just because Python reprs a string with backslashes, doesn't mean it's actually added any slashes to the string, it may just be showing special characters escaped.

Using an example from the Python tutorial:

>>> len('"Isn't," she said.')
18
>>> len('''"Isn't," she said.''')
18

Even though the second string appears one character shorter because it doesn't have a backslash in it, it's actually the same length -- the backslash is just to escape the single quote in the single quoted string.

Another example:

>>> for c in '''"Isn't," she said.''':
...     sys.stdout.write(c)
... 
"Isn't," she said.
>>> 

If you don't let Python format the string, you can see the string hasn't been changed, it was just Python trying to display it unambiguously.

See the tutorial section on strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...