forked from cool-RR/python_toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase_conversions.py
More file actions
71 lines (46 loc) · 1.54 KB
/
case_conversions.py
File metadata and controls
71 lines (46 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Defines functions for converting between different string conventions.'''
import sys
import re
def camel_case_to_space_case(s):
'''
Convert a string from camelcase to spacecase.
Example: camelcase_to_underscore('HelloWorld') == 'Hello world'
'''
if s == '': return s
process_character = lambda c: (' ' + c.lower()) if c.isupper() else c
return s[0] + ''.join(process_character(c) for c in s[1:])
def camel_case_to_lower_case(s):
'''
Convert a string from camel-case to lower-case.
Example:
camel_case_to_lower_case('HelloWorld') == 'hello_world'
'''
return re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', s). \
lower().strip('_')
def lower_case_to_camel_case(s):
'''
Convert a string from lower-case to camel-case.
Example:
camel_case_to_lower_case('hello_world') == 'HelloWorld'
'''
s = s.capitalize()
while '_' in s:
head, tail = s.split('_', 1)
s = head + tail.capitalize()
return s
def camel_case_to_upper_case(s):
'''
Convert a string from camel-case to upper-case.
Example:
camel_case_to_lower_case('HelloWorld') == 'HELLO_WORLD'
'''
return camel_case_to_lower_case(s).upper()
def upper_case_to_camel_case(s):
'''
Convert a string from upper-case to camel-case.
Example:
camel_case_to_lower_case('HELLO_WORLD') == 'HelloWorld'
'''
return lower_case_to_camel_case(s.lower())