Project

General

Profile

1
# String manipulation
2

    
3
import re
4

    
5
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

    
13
def ensure_newl(str_): return str_.rstrip()+'\n'
14

    
15
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
def remove_extra_newl(str_):
20
    if is_multiline(str_): return str_
21
    else: return str_.rstrip()
22

    
23
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
24

    
25
def cleanup(str_): return std_newl(str_.strip())
26

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