@author jackzhenguo @desc @date 2019/8/12
99 批量转化为驼峰格式(Camel)
数据库字段名批量转化为驼峰格式
分析过程
# 用到的正则串讲解 # \s 指匹配: [ \t\n\r\f\v] # A|B:表示匹配A串或B串 # re.sub(pattern, newchar, string): # substitue代替,用newchar字符替代与pattern匹配的字符所有.
# title(): 转化为大写,例子: # 'Hello world'.title() # 'Hello World'
# print(re.sub(r"\s|_|", "", "He llo_worl\td")) s = re.sub(r"(\s|_|-)+", " ", 'some_database_field_name').title().replace(" ", "") #结果: SomeDatabaseFieldName
# 可以看到此时的第一个字符为大写,需要转化为小写 s = s[0].lower()+s[1:] # 最终结果
整理以上分析得到如下代码:
import re def camel(s): s = re.sub(r"(\s|_|-)+", " ", s).title().replace(" ", "") return s[0].lower() + s[1:] # 批量转化 def batch_camel(slist): return [camel(s) for s in slist]
测试结果:
s = batch_camel(['student_id', 'student\tname', 'student-add']) print(s) # 结果 ['studentId', 'studentName', 'studentAdd']