# utillib.py
#
# misc useful functions
"""This Module implements some useful utility functions.
Contains the following functions:
o capwords(string):
better string.capwords(), works with locale set
o die(err_string, exit_code=1)
like perl's die() function
o string_reverse(string):
just what the names says
o string_usplit(s, sep=' ', maxsplit=0, step=1):
like string.split() but with extra parameter for step value
"""
import re, string, sys
def warn(msg):
sys.stderr.write(msg + '\n')
def die(err_string, exit_code=1):
"""Prints error message to stderr and exits with exit code = exit_code."""
warn(err_string)
sys.exit(exit_code)
def confirm(msg):
try:
result = raw_input("%s (yes/No) " % (msg))
except EOFError:
print
return 0
if string.upper(result) in ['Y', 'YES', 'YUP', 'YEP']:
return 1
else:
return 0
def _capmatch(m):
return string.capitalize(m.group(0))
# if you don't want all uppercase words to be converted
#return string.upper(m.group(0)[0]) + m.group(0)[1:]
def capwords(s):
"""Capitalise first letter of each word in string."""
p = re.compile(r"""
\b([\w']+)\b # apostrophes inside word-boundaries
# are ok
""", re.VERBOSE|re.LOCALE)
return p.sub(_capmatch, s)
def string_reverse(s):
"""Reverses string, converting it to a list, reversing and re-joining it."""
s = list(s)
s.reverse()
return string.join(s, '')
def string_usplit(s, sep=' ', maxsplit=0, step=1):
"""Split string s at maxsplit ocurrences of sep at every step index."""
l = []; subs = 0; lastidx = 0
for i in range(0, len(s), step):
if s[i:i+len(sep)] == sep:
l.append(s[lastidx:i])
lastidx = i+len(sep)
subs += 1
if subs >= maxsplit and maxsplit != 0: break
l.append(s[lastidx:])
return l