Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have an equivalent of Perl's qq?

Tags:

python

perl

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?

like image 597
Gnubie Avatar asked Oct 17 '25 16:10

Gnubie


2 Answers

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'
like image 100
jonrsharpe Avatar answered Oct 20 '25 06:10

jonrsharpe


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!'
like image 25
Avinash Raj Avatar answered Oct 20 '25 04:10

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!