我写了下面的函数将下划线转换为驼峰与小写的第一个字,即“get_this_value” – > “getThisValue”。我还要求保留前导和尾随的下划线,以及双(三等)下划线,如果有的话,即。
"_get__this_value_" -> "_get_ThisValue_".
代码:
def underscore_to_camelcase(value):
output = ""
first_word_passed = False
for word in value.split("_"):
if not word:
output += "_"
continue
if first_word_passed:
output += word.capitalize()
else:
output += word.lower()
first_word_passed = True
return output
我感觉上面的代码写的非Pythonic风格,虽然它的工作原理,所以看看如何简化代码,并使用列表解释等。