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