473,406 Members | 2,745 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,406 software developers and data experts.

Inelegant

Dan

I've just begun playing with Python, and so far I like what I see.
It's a very elegant language. But I've found something that's, well,
a bit ugly. Maybe someone can point out to me where I'm wrong.

If you use triple quotes to define a string, then the newlines are
implicitly included. This is a very nice feature. But if you're
inside a function or statement, then you'll want the string to be
positioned along that indentation. And the consequences of this is
that the string will include those indentations.

For example:

def SomeFunction()
if SomeCondition:
MyString =
"""
The quick brown fox
"""
print MyString

The output will be:

The quick brown fox

But what you really want is:

The quick brown fox

The way around it is to write the function thus:

def SomeFunction()
if SomeCondition:
MyString =
"""
The quick brown fox
"""
print MyString

But that's just ugly. It seems to me that the string should be
interpreted with the edge along the indentation line, not from the
start of the line. But that would probably create other problems.

Dan
Jul 18 '05 #1
4 1053
On Thursday 14 April 2005 02:03 am, Dan wrote:
If you use triple quotes to define a string, then the newlines are
implicitly included. This is a very nice feature. But if you're
inside a function or statement, then you'll want the string to be
positioned along that indentation. And the consequences of this is
that the string will include those indentations.
[...]
But that's just ugly.


Yeah, it's definitely a wart. So much so that recent Python
distributions include a function to fix it:
from textwrap import dedent
string_block = dedent(""" .... This string will have the leading
.... spaces removed so that it doesn't
.... have to break up the indenting.
.... """) string_block "\nThis string will have the leading\nspaces removed so that it doesn't\nhave to break up the indenting.\n" print string_block


This string will have the leading
spaces removed so that it doesn't
have to break up the indenting.


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 18 '05 #2
On Thu, 14 Apr 2005 02:43:40 -0500, Terry Hancock <ha*****@anansispaceworks.com> wrote:
On Thursday 14 April 2005 02:03 am, Dan wrote:
If you use triple quotes to define a string, then the newlines are
implicitly included. This is a very nice feature. But if you're
inside a function or statement, then you'll want the string to be
positioned along that indentation. And the consequences of this is
that the string will include those indentations.
[...]
But that's just ugly.


Yeah, it's definitely a wart. So much so that recent Python
distributions include a function to fix it:
from textwrap import dedent
string_block = dedent("""... This string will have the leading
... spaces removed so that it doesn't
... have to break up the indenting.
... """) string_block"\nThis string will have the leading\nspaces removed so that it doesn't\nhave to break up the indenting.\n" print string_block
This string will have the leading
spaces removed so that it doesn't
have to break up the indenting.


I never liked any of the solutions that demand bracketing the string with expression brackets,
but I just had an idea ;-)
class Dedent(object): ... def __init__(self, **kw): self.kw = kw
... def __add__(self, s):
... lines = s.splitlines()[1:]
... margin = self.kw.get('margin', 0)*' '
... mnow = min(len(L)-len(L.lstrip()) for L in lines)
... return '\n'.join([line[mnow:] and margin+line[mnow:] or '' for line in lines])
...
...

Normally you wouldn't pass **kw in like this,
you'd just write
mystring = Dedent()+\

or

mystring = Dedent(margin=3)+\

but I wanted to control the print. Note the the first line, unless you escape it (ugly there)
is zero length and therefore has zero margin, which subverts the other shifting, so I just drop that line.
You have to live with the backslash after the + as payment for preferring not to have parentheses ;-)
def foo(**kw): ... mystring = Dedent(**kw)+\
... """
... This makes
... for a cleaner isolation
... of the string IMO.
... """
... return mystring
... print '----\n%s----'%foo() ----
This makes
for a cleaner isolation
of the string IMO.
---- print '----\n%s----'%foo(margin=3)

----
This makes
for a cleaner isolation
of the string IMO.
----

Regards,
Bengt Richter
Jul 18 '05 #3
gry
I sometimes use the implicit literal string concatenation:

def SomeFunction():
if SomeCondition:
MyString = 'The quick brown fox ' \
'jumped over the ' \
'lazy dog'
print MyString

SomeFunction()
The quick brown fox jumped over the lazy dog
It looks pretty good, I think. One could use triple quotes too, if the
string
contains quotes.

-- George

Jul 18 '05 #4
Bengt Richter wrote:
I never liked any of the solutions that demand bracketing the string with expression brackets,
but I just had an idea ;-)


Or for an even more twisted idea:
from textwrap import dedent

class _Dedent(type):

def __new__(cls, name, bases, dict):
if name == "*": # for bootstrapping
return type.__new__(cls, name, bases, dict)
return dedent(dict['__doc__'])

DedentedString = _Dedent("*", (), {})

#
# Usage example
#

class foo(DedentedString):
"""
This is a dedented (or perhaps demented?) string.
It spans multiple lines.
"""

print type(foo)
print foo

The output is:

<type 'str'>

This is a dedented (or perhaps demented?) string.
It spans multiple lines.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #5

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

Similar topics

23
by: JC | last post by:
I am very new to programming and learning on my own. Why do I keep getting duplicate values using this code? I want to shuffle a deck of 52 cards. The logic seems right to me. Randomize For...
6
by: Doug Tolton | last post by:
I have a function that returns a tuple: def checkdoc(self, document): blen = document bates = document normal, truncated, semicolon = 0,0,0 for bat in bates: if len(bat) == 2 * blen:...
8
by: VisionSet | last post by:
I have already posted this under 'Simple table organisation question' here is a more lucid version. It will be under MySQL v4.0 which now supports unions Consider 2 entities - books & authors...
2
by: K | last post by:
Hi all; I don't think this is a VC compiler question, so I am asking this here. I did hunt around the web and Stroustrup before posting, but found no references to this problem. I have a base...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...

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.