在python字符串中同时具有单引号和双引号 [英] Having both single and double quotation in a python string

查看:144
本文介绍了在python字符串中同时具有单引号和双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中创建一个包含单引号和双引号的字符串 -- ('".我需要这个表达式的原因是用作某些外部批处理命令的输入.但是,python 总是自动将其更正为 (\' ").我想知道是否有办法将双引号和单引号放在一起.谢谢.

解决方案

使用三重引号.

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

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

请记住,仅仅因为 Python repr 是一个带反斜杠的字符串,并不意味着它实际上在字符串中添加了任何斜杠,它可能只是显示转义的特殊字符.

使用 Python 教程中的示例:

<预><代码>>>>len('不是,"她说.')18>>>len('''不是,"她说.''')18

即使第二个字符串由于没有反斜杠而显得短了一个字符,但它实际上是相同的长度——反斜杠只是为了转义单引号字符串中的单引号.

另一个例子:

<预><代码>>>>for c in '''不是,"她说.''':... sys.stdout.write(c)...不是,"她说.>>>

如果你不让 Python 格式化字符串,你可以看到字符串没有改变,只是 Python 试图明确地显示它.

请参阅有关字符串的教程部分.

Hi I'm trying to have a string that contains both single and double quotation in python -- ('"). The reason I need this expression is to use as an input to some external batch command. 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. Thanks.

解决方案

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.

这篇关于在python字符串中同时具有单引号和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆