下划线转驼峰
方法一
def to_camelcase(text):
arr = filter(None, text.lower().split('_'))
res = ''
j = 0
for i in arr:
if j == 0:
res = i
else:
res = res + i[0].upper() + i[1:]
j += 1
return res
该方法存在问题:
'HelloWorldWorld' -> 'helloworldworld'
方法二
import re
def to_camelcase(name: str) -> str:
"""下划线转驼峰(小驼峰)"""
return re.sub(r'(_[a-z])', lambda x: x.group(1)[1].upper(), name)
该方法存在问题:
'hello_world__world' -> 'helloWorld_World'
驼峰转下划线
import re
def to_underscore(name: str) -> str:
"""驼峰转下划线"""
if '_' not in name:
name = re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
else:
raise ValueError(f'{name}字符中包含下划线,无法转换')
return name.lower()
该方法存在问题:连续两个大写字母无法进行区分
'HelloWorldWOrld' -> 'hello_world_world'
'HelloWorldWorld' -> 'hello_world_world'
import re
def to_underscore(name: str) -> str:
"""驼峰转下划线"""
if '_' not in name:
name = re.sub(r'([A-Z])([A-Z])', r'\1_\2', name)
name = re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
else:
raise ValueError(f'{name}字符中包含下划线,无法转换')
return name.lower()
'HelloWorldWOrld' -> 'hello_world_w_orld'
'HelloWorldWorld' -> 'hello_world_world'
自由互转
import re
def _name_convert_to_camel(name: str) -> str:
"""下划线转驼峰(小驼峰)"""
return re.sub(r'(_[a-z])', lambda x: x.group(1)[1].upper(), name)
def _name_convert_to_snake(name: str) -> str:
"""驼峰转下划线"""
if '_' not in name:
name = re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
else:
raise ValueError(f'{name}字符中包含下划线,无法转换')
return name.lower()
def name_convert(name: str) -> str:
"""驼峰式命名和下划线式命名互转"""
is_camel_name = True # 是否为驼峰式命名
if '_' in name and re.match(r'[a-zA-Z_]+$', name):
is_camel_name = False
elif re.match(r'[a-zA-Z]+$', name) is None:
raise ValueError(f'Value of "name" is invalid: {name}')
return _name_convert_to_snake(name) if is_camel_name else _name_convert_to_camel(name)
if __name__ == '__main__':
print(name_convert('HelloWorldWorld')) # -> hello_world_world
print(name_convert('hello_world_world')) # -> helloWorldWorld
参考:
https://blog.csdn.net/qq_31998745/article/details/113727839
https://www.cnblogs.com/zipon/p/10784264.html