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
|
|
|
string = re.sub("^(_*)(.)", |
21
|
|
|
lambda match: match.group(1) + match.group(2).lower(), |
22
|
|
|
string) |
23
|
|
|
return re.sub("(?<=[^_])_+([^_])", |
24
|
|
|
lambda match: match.group(1).upper(), |
25
|
|
|
string) |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
def to_pascalcase(string): |
29
|
|
|
""" |
30
|
|
|
Converts the given to string pascal-case. |
31
|
|
|
|
32
|
|
|
>>> to_pascalcase('hello_world') |
33
|
|
|
'HelloWorld' |
34
|
|
|
>>> to_pascalcase('__init__file__') |
35
|
|
|
'__InitFile__' |
36
|
|
|
>>> to_pascalcase('') |
37
|
|
|
'' |
38
|
|
|
>>> to_pascalcase('AlreadyPascalCase') |
39
|
|
|
'AlreadyPascalCase' |
40
|
|
|
|
41
|
|
|
:param string: The string to convert. |
42
|
|
|
:return: The pascal-cased string. |
43
|
|
|
""" |
44
|
|
|
string = re.sub("^(_*)(.)", |
45
|
|
|
lambda match: match.group(1) + match.group(2).upper(), |
46
|
|
|
string) |
47
|
|
|
return re.sub("(?<=[^_])_+([^_])", |
48
|
|
|
lambda match: match.group(1).upper(), |
49
|
|
|
string) |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
def to_snakecase(string): |
53
|
|
|
""" |
54
|
|
|
Converts the given to string to snake-case. |
55
|
|
|
|
56
|
|
|
>>> to_snakecase('HelloWorld') |
57
|
|
|
'hello_world' |
58
|
|
|
>>> to_snakecase('__Init__File__') |
59
|
|
|
'__init_file__' |
60
|
|
|
>>> to_snakecase('') |
61
|
|
|
'' |
62
|
|
|
>>> to_snakecase('already_snake_case') |
63
|
|
|
'already_snake_case' |
64
|
|
|
|
65
|
|
|
:param string: The string to convert. |
66
|
|
|
:return: The snake-cased string. |
67
|
|
|
""" |
68
|
|
|
string = re.sub("^(_*)([^_])", |
69
|
|
|
lambda match: match.group(1) + match.group(2).lower(), |
70
|
|
|
string) |
71
|
|
|
string = re.sub("(?<=[^_])_+([^_])", |
72
|
|
|
lambda match: "_" + match.group(1).lower(), |
73
|
|
|
string) |
74
|
|
|
return re.sub("[A-Z]", |
75
|
|
|
lambda match: "_" + match.group(0).lower(), |
76
|
|
|
string) |
77
|
|
|
|