程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python converts hump string to underscore form

編輯:Python

1. Regular detect whether the string has upper case letters ;

2. If so, turn it to lowercase and underline it , Replace old uppercase characters with new characters ;

def turn_param_style(self, params: dict):
'''
Change the hump form of the parameter name to the underscore form
@param params:
@return:
'''
temp_dict = {}
for name, value in params.items():
temp_name = ""
if re.search("[A-Z]", name):
capital_letters = re.findall("[A-Z]", name)
for c in capital_letters:
lower_c = c.lower()
r_str = "_" + lower_c
temp_name = name.replace(c, r_str)
else:
temp_name = name
temp_dict.update({temp_name: value})
return temp_dict

Other conversion methods , here The hump characters are not converted to lowercase

Conditions that become underlined
① We can't see anything from the first one , All I know is that they are all lowercase
② From the second we get the message : The current letter is capitalized , The first letter is lowercase , Need to add in the middle ’_’
③ From the third we get the message : The current letter is capitalized , The first letter is also capitalized , The last letter is lowercase , You need to add... Between the current letter and the previous letter ’ _ ’
④ The resulting output is all lowercase , We regard this as a secondary factor , Finally, they are converted to lowercase

def turn_param_style(self, params: dict):
'''
Change the hump form of the parameter name to the underscore form
@param params:
@return:
'''
temp_dict = {}
for name, value in params.items():
new_name = ""
name += " " # To prevent data overflow
for i in range(len(name) - 1):
if i == 0:
new_name += name[i]
elif name[i].isupper() and name[i - 1].islower():
new_name += "_" + name[i]
# If you don't add name += " ", The index is out of bounds
elif name[i].isupper() and name[i - 1].isupper() and name[i + 1].islower():
new_name += "_" + name[i]
else:
new_name += name[i]
temp_dict.update({new_name: value})
return temp_dict

Reference resources :

【Python】 Hump variables are converted to underscores _InceptionZ The blog of -CSDN Blog _python Hump underline


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved