473,320 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

multiline snippets with triple quotes

I sometimes use triple quotes in order to produce snippets of multiline
code, like that:

if output == html:
snip = '''<html>
<head><title>Hello, World</title></head>
<body bgcolor="aqua"><h1>What's up?</h1>
</html>'''
else:
snip = 'Hello!'

This has the advantage that you don't need to care for inserting newlines
and escaping quotes and is very readable.

However, the triple quoted strings will also contain the indentation of the
Python block. It would not really matter here, since whitespace is ignored
in this case, but there could be situations where whitespace at the
beginning of the lines would matter, and it simply makes no sense to carry
over the identation in most cases.

Of course, I could simply unindent the triple quoted snippets, but then the
Python code starts to become unreadable, if you have many of such snippets
in deeply indented blocks. And isn't bad indentation something that Python
usually forbids "by force" even?

So, what would be the pythonic way to implement such multiline snippets?

Gtx
Chris
Jul 18 '05 #1
8 3202
Christoph Zwerschke wrote:
So, what would be the pythonic way to implement such multiline snippets?


Define them externally to that code block. Either put
them above the function, or at the top of the module,
or have them read from an external file, with the
best approach being dependent on the precise situation
at hand. For example, if you have only one or two
such things, just use parentheses and single quotes
instead of the triple quoting, while if you have a
bunch of them but don't want to read them from a file,
put them in a separate module and just import and
reference them as required.

-Peter
Jul 18 '05 #2
Christoph Zwerschke wrote:
I sometimes use triple quotes in order to produce snippets of multiline
code, like that:

if output == html:
snip = '''<html>
<head><title>Hello, World</title></head>
<body bgcolor="aqua"><h1>What's up?</h1>
</html>'''
else:
snip = 'Hello!'


[...]
So, what would be the pythonic way to implement such multiline snippets?


IIRC, sequential strings with only whitespace in between them are
automatically concatenated. So the above could be equivalently written as:

if output == html:
snip = "<html>\n"
"<head><title>Hello, World</title></head>\n"
"<body bgcolor="aqua"><h1>What's up?</h1>\n"
"</html>\n"
else:
snip = 'Hello!'
This does have the disadvantage of requiring explicit newlines, however.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #3
On Thu, 12 Aug 2004, Christoph Zwerschke wrote:
So, what would be the pythonic way to implement such multiline snippets?


The textwrap.dedent() function is provided for just this purpose:

from textwrap import dedent

if output == html:
snip = dedent('''\
<html>
<head><title>Hello, World</title></head>
<body bgcolor="aqua"><h1>What's up?</h1>
</html>''')
else:
snip = 'Hello!'

textwrap.dedent() removes uniform indentation from the beginning of each
line in the string, so you can still insert desired indents in a natural
way. Note the backslash after the opening quote, and how the actual
string starts on the next line: dedent() isn't as smart as pydoc when it
comes to uniformly indenting strings; it doesn't know to skip the first
line (this helps with more general usage, though).

Jul 18 '05 #4

On Aug 12, 2004, at 4:06 PM, Christopher T King wrote:
The textwrap.dedent() function is provided for just this purpose:

from textwrap import dedent

if output == html:
snip = dedent('''\
<html>
<head><title>Hello, World</title></head>
<body bgcolor="aqua"><h1>What's up?</h1>
</html>''')
else:
snip = 'Hello!'

Can dedent capture indents or tabs also...
I noticed that if I do the following:
snip = '''<html>blah blah
</html>'''
Tabs are included with snip.

Is there a heredocs (don't know why it's called that) equivalent in
Python?

Thanks in advance.

Jul 18 '05 #5
> IIRC, sequential strings with only whitespace in between them are
automatically concatenated.
Yes, but you have to add either brackets around everything or backslashes at
the line ends, otherwise the lines are not kept together.
This does have the disadvantage of requiring explicit newlines, however.


Yes, plus you need to escape the double quotes.

These three disadvantages are why I wanted to use triple quotes.

Chris
Jul 18 '05 #6
> The textwrap.dedent() function is provided for just this purpose:

Thanks. That was the thing I was looking for, though it's a big ugly, plus
it eats some unnecessary CPU cycles at run time. But I think one can live
with that.

Chris
Jul 18 '05 #7
On Thu, 12 Aug 2004, gohaku wrote:
Can dedent capture indents or tabs also...
I noticed that if I do the following:
snip = '''<html>blah blah
</html>'''
Tabs are included with snip.
dedent() will return that string as is, since the <html> tag is already in
the left-most position. If you do something like this, however:

snip = '''\
<html>blah blah
</html>'''

dedent() will flush the <html> tag left, and the </html> tag will be
indented by one tab (since it has a one-tab indent relative to <html>).
Is there a heredocs (don't know why it's called that) equivalent in
Python?


AFAIK, triple quotes do everything heredocs do (but with a cleaner
syntax!); the following produce identical output:

bash heredocs:

echo -n <<EOF
Some text.
Woo!
The end.
EOF

Python triple quotes:

print '''\
Some text.
Woo!
The end.'''

Jul 18 '05 #8
On Fri, Aug 13, 2004 at 09:22:38AM -0400, Christopher T King wrote:

AFAIK, triple quotes do everything heredocs do (but with a cleaner
syntax!); the following produce identical output:

bash heredocs:

echo -n <<EOF
Some text.
Woo!
The end.
EOF

Python triple quotes:

print '''\
Some text.
Woo!
The end.'''
what about
cat <<-EOF 1
2
3
EOF

1
2
3

--
John Lenton (jo**@grulic.org.ar) -- Random fortune:
<JHM> Somehow I have more respect for 14 year old Debian developers than
14 year old Certified Microsoft Serfs.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBHemBgPqu395ykGsRAqfKAJ9T/EjsfspD97012cUT++X5kwl7jwCgssxt
UiroR8OI+dNGDF3J1Ap6F/c=
=QuNS
-----END PGP SIGNATURE-----

Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Rasmus Fogh | last post by:
Dear All, I need a way of writing strings or arbitrary Python code that will a) allow the strings to be read again unchanged (like repr) b) write multiline strings as multiline strings instead...
3
by: Anthony Roberts | last post by:
property = re.compile("""(?P<name>+)="(?P<value>.*?)""""re.I) This doesn't work because the closing quote in my regex forms the first quote of a triple quote to end the string... property =...
7
by: Brian van den Broek | last post by:
Hi all, I'm posting partly so my problem and solution might be more easily found by google, and partly out of mere curiosity. I've just spent a frustrating bit of time figuring out why pydoc...
32
by: Elliot Temple | last post by:
Hi I have two questions. Could someone explain to me why Python is case sensitive? I find that annoying. Also, why aren't there multiline comments? Would adding them cause a problem of some...
3
by: Michele Simionato | last post by:
I am getting trouble with nested triple quoted strings in doctest. For instance $ cat x.py """ >>> dummy = ''' something here ''' """
5
by: ian | last post by:
Hi, I am currently using a Javascript function to dissallow the enter key on my ASP.NET (2.0) web page, as follows: function fnTrapKP(){ if (document.all) { if (event.keyCode == 13) {
40
by: Edward Elliott | last post by:
At the risk of flogging a dead horse, I'm wondering why Python doesn't have any multiline comments. One can abuse triple-quotes for that purpose, but that's obviously not what it's for and doesn't...
9
by: John Salerno | last post by:
How do you make a single string span multiple lines, but also allow yourself to indent the second (third, etc.) lines so that it lines up where you want it, without causing the newlines and tabs or...
8
by: Lawrence D'Oliveiro | last post by:
If triple-quoted strings had the Python-nature, then they would take indentation into account. Thus: """this is a multi-line string.""" would be equivalent to
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.