473,659 Members | 2,920 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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>He llo, 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 3224
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>He llo, 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>H ello, 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>He llo, 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>He llo, 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.or g.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)

iD8DBQFBHemBgPq u395ykGsRAqfKAJ 9T/EjsfspD97012cUT ++X5kwl7jwCgssx t
UiroR8OI+dNGDF3 J1Ap6F/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
1951
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 of escaping the \n's. A repr function that output triple-quoted strings with explicit (non-escaped) linebreaks would be perfect.
3
1977
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 = re.compile("""(?P<name>+)=("(?P<value>.*?)")""", re.I) This mucks up stuff I want to do later. I've thought about it for a while, and except for changing it to a
7
3969
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 didn't extract a description from my module docstrings. Even though I had a well formed docstring (one line, followed by a blank line, followed by the rest of the docstring), when I ran Module docs, my modules showed up as having "no description"....
32
3142
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 sort? Thanks, Elliot
3
2530
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
4579
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
4611
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 nest properly. ML has a very elegant system for nested comments with (* and *). Using an editor to throw #s in front of every line has limitations. Your editor has to support it and you have to know how to use that feature. Not exactly...
9
3171
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 spaces to be added to the string as well? Example (pretend this is all on one line): self.DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n'
8
4269
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
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8747
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.