Package Ganga :: Package Utility :: Module strings
[hide private]
[frames] | no frames]

Source Code for Module Ganga.Utility.strings

 1  'Utilities for string manipulation' 
 2   
 3  import re 
 4  _ident_expr = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$') 
 5   
6 -def is_identifier(x):
7 'return true if a string is valid python identifier' 8 return bool(_ident_expr.match(x))
9
10 -def drop_spaces(x):
11 'drop all spaces from a string, so that "this is an example " becomes "thisisanexample"' 12 return x.replace(' ','')
13
14 -class ItemizedTextParagraph:
15 """Format a paragraph with itemized text. 16 17 <------------------ width -------------> 18 19 Example: (*) 20 (#) 21 item1 (**) description1 22 (#) 23 item2 (**) description2 which is 24 very long but breaks OK 25 (#) 26 item3 (**) 27 28 (*) is a head of the paragraph 29 (**) is a separator 30 (#) is a line separator 31 """
32 - def __init__(self,head,width=80,separator=' ',linesep=None):
33 self.head = head 34 self.items = [] 35 self.desc = [] 36 self.width = width 37 self.sep = separator 38 self.linesep = linesep
39
40 - def addLine(self,item,description):
41 self.items.append(item) 42 self.desc.append(description)
43
44 - def getString(self):
45 46 maxitem = 0 47 for it in self.items: 48 if len(it) > maxitem: 49 maxitem = len(it) 50 51 indent = ' '*(len(self.head)/2) 52 53 buf = self.head + '\n' 54 55 import Ganga.Utility.external.textwrap as textwrap 56 57 for it,d in zip(self.items,self.desc): 58 if not self.linesep is None: 59 buf += self.linesep + '\n' 60 buf2 = '%-*s%s%s' % (maxitem,it,self.sep,d) 61 buf += textwrap.fill(buf2,width=self.width,initial_indent=indent,subsequent_indent=' '*(maxitem+len(self.sep))+indent) + '\n' 62 63 return buf
64 65 66 67 68 if __name__ == "__main__": 69 assert(is_identifier('a')) 70 assert(not is_identifier('1')) 71 assert(is_identifier('a1')) 72 assert(not is_identifier('a1 ')) 73 assert(not is_identifier(' a')) 74 assert(not is_identifier('a b')) 75 assert(is_identifier('_')) 76 77 assert(drop_spaces(' a b c ') == 'abc') 78 assert(drop_spaces('abc') == 'abc') 79 80 it = ItemizedTextParagraph('Functions:') 81 it.addLine('dupa','jerza;fdlkdfs;lkdfkl;') 82 it.addLine('dupaduuza','jerza;fdlkdfs;lkdfkl;') 83 it.addLine('d','jerza;fdlkdfs;lkdfkl;') 84 85 print it.getString() 86 87 print 'strings: Test Passed OK' 88