【发布时间】:2015-04-10 11:08:22
【问题描述】:
使用qq,Perl 允许几乎任何字符用作引号来定义包含' 和" 的字符串,而无需转义它们:
qq(She said, "Don't!")
qq¬And he said, "I won't."¬
(特别方便,因为我的键盘有 ¬ 几乎从未使用过)。
Python 有没有等价物?
【问题讨论】:
使用qq,Perl 允许几乎任何字符用作引号来定义包含' 和" 的字符串,而无需转义它们:
qq(She said, "Don't!")
qq¬And he said, "I won't."¬
(特别方便,因为我的键盘有 ¬ 几乎从未使用过)。
Python 有没有等价物?
【问题讨论】:
您不能将任意字符定义为引号,但如果您需要在字符串中同时使用' 和",您可以使用多行字符串:
>>> """She said "that's ridiculous" and I agreed."""
'She said "that\'s ridiculous" and I agreed.'
但是请注意,如果您使用的引号类型也是字符串中的最后一个字符,那么 Python 会感到困惑:
>>> """He yelled "Whatever's the matter?""""
SyntaxError: EOL while scanning string literal
所以你必须在这种情况下切换:
>>> '''He yelled "Whatever's the matter?"'''
'He yelled "Whatever\'s the matter?"'
纯粹作为替代方案,您可以将字符串拆分为具有和不具有每种引号类型的部分,并依赖 Python 隐式连接连续字符串:
>>> "This hasn't got double quotes " 'but "this has"'
'This hasn\'t got double quotes but "this has"'
>>> "This isn't " 'a """very""" "attractive" approach'
'This isn\'t a """very""" "attractive" approach'
【讨论】:
您可以使用三个单引号或三个双引号。
>>> s = '''She said, "Don't!"'''
>>> print(s)
She said, "Don't!"
>>> s = """'She sai"d, "Don't!'"""
>>> print(s)
'She sai"d, "Don't!'
【讨论】:
''' 是字符串分隔符 :)
我刚刚问自己,python 中的 quote() 方法在哪里?特别是 Perl 的 qXXX 糖。在 urllib 中找到一个 quote() 但这不是我想要的 - 那就是简单地在字符串本身中引用字符串。然后它击中了我:
some_string = repr(some_string)
repr 内置将始终正确引用字符串。它会得到单引号。 Perl 有双引号的倾向。
【讨论】: