Project

General

Profile

1
# String manipulation
2

    
3
import codecs
4
import re
5

    
6
import util
7

    
8
##### Debug printing
9

    
10
class DebugPrintable:
11
    def __str__(self): return util.class_name(self)+repr(self.__dict__)
12
    
13
    def __repr__(self): return str(self)
14

    
15
##### Parsing
16

    
17
def split(sep, str_):
18
    '''Returns [] if str_ == ""'''
19
    if str_ == '': return []
20
    else: return str_.split(sep)
21

    
22
def remove_prefix(prefix, str_, removed_ref=None):
23
    if removed_ref == None: removed_ref = [False]
24
    
25
    removed_ref[0] = str_.startswith(prefix)
26
    if removed_ref[0]: return str_[len(prefix):]
27
    else: return str_
28

    
29
def remove_prefixes(prefixes, str_):
30
    for prefix in prefixes: str_ = remove_prefix(prefix, str_)
31
    return str_
32

    
33
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
34

    
35
def remove_suffix(suffix, str_, removed_ref=None):
36
    if removed_ref == None: removed_ref = [False]
37
    
38
    removed_ref[0] = str_.endswith(suffix)
39
    if removed_ref[0]: return str_[:-len(suffix)]
40
    else: return str_
41

    
42
def contains_any(haystack, needles):
43
    for needle in needles:
44
        if haystack.find(needle) >= 0: return True
45
    return False
46

    
47
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
48

    
49
##### Unicode
50

    
51
unicode_reader = codecs.getreader('utf_8')
52

    
53
def to_unicode(str_):
54
    if isinstance(str_, unicode): return str_
55
    encodings = ['utf_8', 'latin_1']
56
    for encoding in encodings:
57
        try: return unicode(str_, encoding)
58
        except UnicodeDecodeError, e: pass
59
    raise AssertionError(encoding+' is not a catch-all encoding')
60

    
61
def ustr(val):
62
    '''Like built-in str() but converts to unicode object'''
63
    if not util.is_str(val): val = str(val)
64
    return to_unicode(val)
65

    
66
##### Line endings
67

    
68
def extract_line_ending(line):
69
    '''@return tuple (contents, ending)'''
70
    contents = remove_suffix('\r', remove_suffix('\n', line))
71
    return (contents, line[len(contents):])
72

    
73
def remove_line_ending(line): return extract_line_ending(line)[0]
74

    
75
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
76

    
77
def is_multiline(str_):
78
    newl_idx = str_.find('\n')
79
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
80

    
81
def remove_extra_newl(str_):
82
    if is_multiline(str_): return str_
83
    else: return str_.rstrip()
84

    
85
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
86

    
87
##### Whitespace
88

    
89
def cleanup(str_): return std_newl(str_.strip())
90

    
91
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
92

    
93
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
94

    
95
##### Control characters
96

    
97
def is_ctrl(char):
98
    '''Whether char is a (non-printable) control character'''
99
    return ord(char) < 32 and not char.isspace()
100

    
101
def strip_ctrl(str_):
102
    '''Strips (non-printable) control characters'''
103
    return ''.join(filter(lambda c: not is_ctrl(c), str_))
(25-25/34)