繁体   English   中英

Python有相当于Perl的qq吗?

[英]Does Python have an equivalent of Perl's qq?

使用qq ,Perl的几乎允许任何字符作为引号来定义包含字符串'"无需转义:

qq(She said, "Don't!")
qq¬And he said, "I won't."¬

(特别方便,因为我的键盘¬几乎从未使用过)。

Python有相同的功能吗?

您可以使用三重单引号或三重双引号。

>>> s = '''She said, "Don't!"'''
>>> print(s)
She said, "Don't!"
>>> s = """'She sai"d, "Don't!'"""
>>> print(s)
'She sai"d, "Don't!'

您不能定义任意字符作为引号,但是如果你需要同时使用'"在字符串中,你可以用多行字符串这样做:

>>> """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'

我只是问自己python中的quote()方法在哪里? 特别是Perl的qXXX糖。 在urllib中找到一个quote(),但这不是我想要的 - 那就是在字符串本身中引用字符串。 然后它就撞到了我:

some_string = repr(some_string)

内置的repr将始终正确引用字符串。 它会得到单引号。 Perl倾向于双引号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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