1
|
# String manipulation
|
2
|
|
3
|
import re
|
4
|
|
5
|
import util
|
6
|
|
7
|
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
|
|
15
|
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
|
def ensure_newl(str_): return str_.rstrip()+'\n'
|
21
|
|
22
|
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
|
def remove_extra_newl(str_):
|
27
|
if is_multiline(str_): return str_
|
28
|
else: return str_.rstrip()
|
29
|
|
30
|
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
|
31
|
|
32
|
def cleanup(str_): return std_newl(str_.strip())
|
33
|
|
34
|
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
|