gpt4 book ai didi

python - 优雅的 Python 函数将 CamelCase 转换为 snake_case?

转载 作者:IT老高 更新时间:2023-10-28 12:06:09 26 4
gpt4 key购买 nike

例子:

>>> 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

添加两个或更多下划线的情况:

def to_snake_case(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
return name.lower()

蛇皮套到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com