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