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

优雅的Python函数将CamelCase转换为snake_case?,第1张

优雅的Python函数将CamelCase转换为snake_case? Camel case to snake case
import rename = '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_caseprint(camel_to_snake('getHTTPResponseCode'))  # get_http_response_preprint(camel_to_snake('HTTPResponseCodeXYZ'))  # http_response_pre_xyz
Snake skin to camel skin
name = 'snake_case_name'name = ''.join(word.title() for word in name.split('_'))print(name)  # SnakeCaseName


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5655519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存