使用qq,Perl允许几乎任何字符用作引号来定义包含'和"不需要转义它们的字符串:
qq(She said, "Don't!")
qq¬And he said, "I won't."¬
Run Code Online (Sandbox Code Playgroud)
(特别方便,因为我的键盘¬几乎从未使用过).
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!'
Run Code Online (Sandbox Code Playgroud)
您不能将任意字符定义为引号,但如果您需要在字符串中同时使用两者',"您可以使用多行字符串来实现:
>>> """She said "that's ridiculous" and I agreed."""
'She said "that\'s ridiculous" and I agreed.'
Run Code Online (Sandbox Code Playgroud)
但是请注意,如果您使用的引号类型也是字符串中的最后一个字符,Python 会感到困惑:
>>> """He yelled "Whatever's the matter?""""
SyntaxError: EOL while scanning string literal
Run Code Online (Sandbox Code Playgroud)
所以你必须在这种情况下切换:
>>> '''He yelled "Whatever's the matter?"'''
'He yelled "Whatever\'s the matter?"'
Run Code Online (Sandbox Code Playgroud)
纯粹作为替代方案,您可以将字符串分成具有和不具有每种引号类型的部分,并依赖 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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1015 次 |
| 最近记录: |