1
|
# String manipulation
|
2
|
|
3
|
import codecs
|
4
|
import re
|
5
|
|
6
|
import util
|
7
|
|
8
|
##### Parsing
|
9
|
|
10
|
def split(sep, str_):
|
11
|
'''Returns [] if str_ == ""'''
|
12
|
if str_ == '': return []
|
13
|
else: return str_.split(sep)
|
14
|
|
15
|
def remove_prefix(prefix, str_):
|
16
|
if str_.startswith(prefix): return str_[len(prefix):]
|
17
|
else: return str_
|
18
|
|
19
|
def remove_prefixes(prefixes, str_):
|
20
|
for prefix in prefixes: str_ = remove_prefix(prefix, str_)
|
21
|
return str_
|
22
|
|
23
|
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
|
24
|
|
25
|
def remove_suffix(suffix, str_):
|
26
|
if str_.endswith(suffix): return str_[:-len(suffix)]
|
27
|
else: return str_
|
28
|
|
29
|
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
|
30
|
|
31
|
##### Unicode
|
32
|
|
33
|
unicode_reader = codecs.getreader('utf_8')
|
34
|
|
35
|
def to_unicode(str_):
|
36
|
if isinstance(str_, unicode): return str_
|
37
|
encodings = ['utf_8', 'latin_1']
|
38
|
for encoding in encodings:
|
39
|
try: return unicode(str_, encoding)
|
40
|
except UnicodeDecodeError, e: pass
|
41
|
raise AssertionError(encoding+' is not a catch-all encoding')
|
42
|
|
43
|
def ustr(val):
|
44
|
'''Like built-in str() but converts to unicode object'''
|
45
|
if not util.is_str(val): val = str(val)
|
46
|
return to_unicode(val)
|
47
|
|
48
|
##### Line endings
|
49
|
|
50
|
def extract_line_ending(line):
|
51
|
'''@return tuple (contents, ending)'''
|
52
|
contents = remove_suffix('\r', remove_suffix('\n', line))
|
53
|
return (contents, line[len(contents):])
|
54
|
|
55
|
def remove_line_ending(line): return extract_line_ending(line)[0]
|
56
|
|
57
|
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
|
58
|
|
59
|
def is_multiline(str_):
|
60
|
newl_idx = str_.find('\n')
|
61
|
return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
|
62
|
|
63
|
def remove_extra_newl(str_):
|
64
|
if is_multiline(str_): return str_
|
65
|
else: return str_.rstrip()
|
66
|
|
67
|
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
|
68
|
|
69
|
##### Whitespace
|
70
|
|
71
|
def cleanup(str_): return std_newl(str_.strip())
|
72
|
|
73
|
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
|
74
|
|
75
|
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
|