text formatting module?

John Hunter jdhunter at nitace.bsd.uchicago.edu
Tue Nov 12 17:32:58 EST 2002


>>>>> "Lance" == Lance  <lbrannma at cablespeed.com> writes:

    Lance> Hi All, I would like to write text that word wraps to two
    Lance> or three levels of tab stops.

I don't know of a module, but something like the following may help:

def get_split_ind(seq, N):
   """seq is a list of words.  Return the index into seq such that 
   len(' '.join(seq[:ind])<=N
   """
   
   sLen = 0
   # todo: use Alex's xrange pattern from the cbook for efficiency
   for (word, ind) in zip(seq, range(len(seq))):
      sLen += len(word) + 1  # +1 to account for the len(' ')
      if sLen>=N: return ind
   return len(seq)
      
   
def wrap(prefix, text, cols):

   pad = ' '*len(prefix.expandtabs())
   available = cols - len(pad)

   seq = text.split(' ')
   Nseq = len(seq)
   ind = 0
   lines = []
   while ind<Nseq:
      lastInd = ind
      ind += get_split_ind(seq[ind:], available)
      lines.append(seq[lastInd:ind])

   # add the prefix to the first line, pad with spaces otherwise
   ret = prefix + ' '.join(lines[0]) + '\n'
   for line in lines[1:]:
      ret += pad + ' '.join(line) + '\n'
   return ret

prefix = 'expandtabs\t'


text = """Expand tabs in a string, i.e. replace them by one or more spaces, depending on the current column and the given tab size.  The column number is reset to zero after each newline occurring in the string. This doesn't understand other non-printing characters or escape sequences.  The tab size defaults to 8.
"""

print wrap(prefix, text, 64)


which prints:



expandtabs	Expand tabs in a string, i.e. replace them by
                one or more spaces, depending on the current
                column and the given tab size.  The column
                number is reset to zero after each newline
                occurring in the string. This doesn't
                understand other non-printing characters or
                escape sequences.  The tab size defaults to
                8.


Hope this helps,
John Hunter




More information about the Python-list mailing list