Do pythons like sugar?
Andrew Dalke
adalke at mindspring.com
Thu Jan 9 02:13:34 EST 2003
Afanasiy wrote:
> I've written this method for a text formatting class...
> But it's ugly as sin. With all those self's I consider
> it much less readable than it could be...
...
> Does Python? eg. `with self do:`
>
> def format( self, width=80 ):
> self.lines = ['']
> i = 0
> for word in self.text.split():
> if self.textwidth(self.lines[i]) + self.textwidth(word) <= width:
> if self.textwidth(self.lines[i]) > 0:
> self.lines[i] += ' '
> self.lines[i] += word
> else:
> i += 1
> self.lines.append(word)
>
Do you really need all those self references? This looks like it should
be a function, as in
def format(text, width = 80):
lines = []
line = ''
for word in text.split():
if len(line) + len(word) <= width:
if line:
line += ' '
line += word
else:
if not line:
raise TypeError("The word %r is more than %d colums!" % \
(word, width))
lines.append(line)
line = ''
return lines
class ...
def ...
self.lines = format(text, 132)
(Note -- I'm using 'len' instead of your 'self.textwidth'. You
could pass in the length function as a parameter if you want.)
If using Python 2.3, see the 'textwrap' module.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list