Project

General

Profile

1
# String manipulation
2

    
3
import codecs
4
import re
5

    
6
import util
7

    
8
unicode_reader = codecs.getreader('utf_8')
9

    
10
def to_unicode(str_):
11
    if isinstance(str_, unicode): return str_
12
    encodings = ['utf_8', 'latin_1']
13
    for encoding in encodings:
14
        try: return unicode(str_, encoding)
15
        except UnicodeDecodeError, e: pass
16
    raise AssertionError(encoding+' is not a catch-all encoding')
17

    
18
def ustr(val):
19
    '''Like built-in str() but converts to unicode object'''
20
    if not util.is_str(val): val = str(val)
21
    return to_unicode(val)
22

    
23
def ensure_newl(str_): return str_.rstrip()+'\n'
24

    
25
def is_multiline(str_):
26
    newl_idx = str_.find('\n')
27
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
28

    
29
def remove_extra_newl(str_):
30
    if is_multiline(str_): return str_
31
    else: return str_.rstrip()
32

    
33
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
34

    
35
def cleanup(str_): return std_newl(str_.strip())
36

    
37
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
(11-11/17)