1 |
73
|
aaronmk
|
# String manipulation
|
2 |
|
|
|
3 |
861
|
aaronmk
|
import re
|
4 |
|
|
|
5 |
1232
|
aaronmk
|
import util
|
6 |
|
|
|
7 |
73
|
aaronmk
|
def to_unicode(str_):
|
8 |
|
|
if isinstance(str_, unicode): return str_
|
9 |
|
|
encodings = ['utf_8', 'latin_1']
|
10 |
|
|
for encoding in encodings:
|
11 |
|
|
try: return unicode(str_, encoding)
|
12 |
|
|
except UnicodeDecodeError, e: pass
|
13 |
|
|
raise AssertionError(encoding+' is not a catch-all encoding')
|
14 |
340
|
aaronmk
|
|
15 |
1232
|
aaronmk
|
def ustr(val):
|
16 |
|
|
'''Like built-in str() but converts to unicode object'''
|
17 |
|
|
if not util.is_str(val): val = str(val)
|
18 |
|
|
return to_unicode(val)
|
19 |
|
|
|
20 |
340
|
aaronmk
|
def ensure_newl(str_): return str_.rstrip()+'\n'
|
21 |
714
|
aaronmk
|
|
22 |
856
|
aaronmk
|
def is_multiline(str_):
|
23 |
|
|
newl_idx = str_.find('\n')
|
24 |
|
|
return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
|
25 |
|
|
|
26 |
860
|
aaronmk
|
def remove_extra_newl(str_):
|
27 |
856
|
aaronmk
|
if is_multiline(str_): return str_
|
28 |
|
|
else: return str_.rstrip()
|
29 |
|
|
|
30 |
714
|
aaronmk
|
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
|
31 |
|
|
|
32 |
|
|
def cleanup(str_): return std_newl(str_.strip())
|
33 |
861
|
aaronmk
|
|
34 |
|
|
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
|