简体   繁体   中英

Does Python have an equivalent of Perl's qq?

Using qq , Perl allows almost any character to be used as quotation marks to define strings containing ' and " without needing to escape them:

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

(especially handy since my keyboard has ¬ which is almost never used).

Does Python have an equivalent?

You could use triple single quotes or triple double quotes.

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

You can't define arbitrary characters as quotes, but if you need to use both ' and " within a string you can do so with a multiline string:

>>> """She said "that's ridiculous" and I agreed."""
'She said "that\'s ridiculous" and I agreed.'

Note, however, that Python will get confused if the quote type you use is also the last character in the string:

>>> """He yelled "Whatever's the matter?""""
SyntaxError: EOL while scanning string literal

so you'd have to switch in that case:

>>> '''He yelled "Whatever's the matter?"'''
'He yelled "Whatever\'s the matter?"'

Purely as an alternative, you could split the string up into parts that do and don't have each quote type and rely on Python implicitly joining consecutive strings:

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

I just asked myself where is quote() method in python? Particularly Perl's qXXX sugar. Found one quote() in urllib but this is not what I wanted - that is to simply quote string in the string itself. And then it hit me:

some_string = repr(some_string)

repr built-in will always quote string properly. It will get single quoted though. Perl had a tendency to double-quote.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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