Completed
Pull Request — master (#2191)
by Mischa
01:53
created

to_camelcase()   A

Complexity

Conditions 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 23
rs 9.0856
1
import re
2
3
4
def to_camelcase(string):
5
    """
6
    Converts the given string to camel-case.
7
8
    >>> to_camelcase('Hello_world')
9
    'helloWorld'
10
    >>> to_camelcase('__Init__file__')
11
    '__initFile__'
12
    >>> to_camelcase('')
13
    ''
14
    >>> to_camelcase('alreadyCamelCase')
15
    'alreadyCamelCase'
16
17
    :param string: The string to convert.
18
    :return:       The camel-cased string.
19
    """
20
    # Use [:1] so we can avoid an `if` that checks for a zero-length string.
21
    string = re.sub("^(_*)(.)",
22
                    lambda match: match.group(1) + match.group(2).lower(),
23
                    string)
24
    return re.sub("(?<=[^_])_+([^_])",
25
                  lambda match: match.group(1).upper(),
26
                  string)
27
28
29
def to_pascalcase(string):
30
    """
31
    Converts the given to string pascal-case.
32
33
    >>> to_pascalcase('hello_world')
34
    'HelloWorld'
35
    >>> to_pascalcase('__init__file__')
36
    '__InitFile__'
37
    >>> to_pascalcase('')
38
    ''
39
    >>> to_pascalcase('AlreadyPascalCase')
40
    'AlreadyPascalCase'
41
42
    :param string: The string to convert.
43
    :return:       The pascal-cased string.
44
    """
45
    # Use [:1] so we can avoid an `if` that checks for a zero-length string.
46
    string = re.sub("^(_*)(.)",
47
                    lambda match: match.group(1) + match.group(2).upper(),
48
                    string)
49
    return re.sub("(?<=[^_])_+([^_])",
50
                  lambda match: match.group(1).upper(),
51
                  string)
52
53
54
def to_snakecase(string):
55
    """
56
    Converts the given to string to snake-case.
57
58
    >>> to_snakecase('HelloWorld')
59
    'hello_world'
60
    >>> to_snakecase('__Init__File__')
61
    '__init_file__'
62
    >>> to_snakecase('')
63
    ''
64
    >>> to_snakecase('already_snake_case')
65
    'already_snake_case'
66
67
    :param string: The string to convert.
68
    :return:       The snake-cased string.
69
    """
70
    # no underscore at beginning if uppercase
71
    #
72
    #"(?<=[^_])_+[^_]|[^_][A-Z]" --> _+a-z
73
    #"^_*[^_]" --> _* + lower()
74
    #""
75
    string = re.sub("^(_*)([^_])",
76
                    lambda match: match.group(1) + match.group(2).lower(),
77
                    string)
78
    string = re.sub("(?<=[^_])_+([^_])",
79
                    lambda match: "_" + match.group(1).lower(),
80
                    string)
81
    return re.sub("[A-Z]",
82
                  lambda match: "_" + match.group(0).lower(),
83
                  string)
84