优雅的Python函数将CamelCase转换为snake

优雅的Python函数将CamelCase转换为snake

This question's answers are a community effort。编辑现有答案以改善此职位。它目前不接受新的答案或互动。








例子:
>>> convert('CamelCase')
'camel_case'

最佳答案

Camel 案到蛇案

import re

name = 'CamelCaseName'
name = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
print(name)  # camel_case_name
如果您执行多次,而上述操作很慢,请事先编译正则表达式:
pattern = re.compile(r'(?<!^)(?=[A-Z])')
name = pattern.sub('_', name).lower()
要专门处理更高级的案件(这不再是可逆的):
def camel_to_snake(name):
  name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
  return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()

print(camel_to_snake('camel2_camel2_case'))  # camel2_camel2_case
print(camel_to_snake('getHTTPResponseCode'))  # get_http_response_code
print(camel_to_snake('HTTPResponseCodeXYZ'))  # http_response_code_xyz
蛇皮到 Camel 皮
name = 'snake_case_name'
name = ''.join(word.title() for word in name.split('_'))
print(name)  # SnakeCaseName

关于python - 优雅的Python函数将CamelCase转换为snake_case?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1175208/

10-11 22:09