Reputation: 2607
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?
Upvotes: 4
Views: 1788
Reputation: 3538
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.
Upvotes: 1
Reputation: 122062
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'
Upvotes: 5
Reputation: 174706
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!'
Upvotes: 5