我编写了下面的函数,将下划线转换为camelcase,第一个单词为小写,即"get_this_value" - >"getThisValue".此外,我还要求保留前导和尾随下划线以及双重(三重等)下划线,如果有的话,即
"_get__this_value_" -> "_get_ThisValue_".
Run Code Online (Sandbox Code Playgroud)
代码:
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
Run Code Online (Sandbox Code Playgroud)
我感觉上面的代码是用非Pythonic风格编写的,虽然它按预期工作,所以看看如何简化代码并使用列表推导等编写代码.
Sie*_*ter 43
这个工作除了将第一个单词保留为小写之外.
def convert(word):
return ''.join(x.capitalize() or '_' for x in word.split('_'))
Run Code Online (Sandbox Code Playgroud)
(我知道这不完全是你所要求的,这个帖子已经很老了,但是因为在Google上搜索这样的转换时它非常突出我以为我会添加我的解决方案,以防它帮助其他人).
Dav*_*ebb 30
你的代码很好.我认为你试图解决的问题是if first_word_passed看起来有点难看.
解决这个问题的一个选择是发电机.我们可以轻松地将此返回一个用于第一个条目,另一个用于所有后续条目.由于Python具有一流的功能,我们可以让生成器返回我们想要用来处理每个单词的函数.
然后我们只需要使用条件运算符,这样我们就可以处理列表解析中双下划线返回的空白条目.
因此,如果我们有一个单词,我们调用生成器来获取用于设置大小写的函数,如果我们不这样做,我们只是使用_保持生成器不变.
def underscore_to_camelcase(value):
def camelcase():
yield str.lower
while True:
yield str.capitalize
c = camelcase()
return "".join(c.next()(x) if x else '_' for x in value.split("_"))
Run Code Online (Sandbox Code Playgroud)
cod*_*ala 18
我个人更喜欢正则表达式.这是一个为我做的技巧:
import re
def to_camelcase(s):
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s)
Run Code Online (Sandbox Code Playgroud)
使用unutbu测试:
tests = [('get__this_value', 'get_ThisValue'),
('_get__this_value', '_get_ThisValue'),
('_get__this_value_', '_get_ThisValue_'),
('get_this_value', 'getThisValue'),
('get__this__value', 'get_This_Value')]
for test, expected in tests:
assert to_camelcase(test) == expected
Run Code Online (Sandbox Code Playgroud)
这是一个更简单的.可能并不适合所有情况,但它符合我的要求,因为我只是将具有特定格式的python变量转换为驼峰式.除了第一个单词之外,这确实很有用.
def underscore_to_camelcase(text):
"""
Converts underscore_delimited_text to camelCase.
Useful for JSON output
"""
return ''.join(word.title() if i else word for i, word in enumerate(text.split('_')))
Run Code Online (Sandbox Code Playgroud)