输入:
to-camel-case
to_camel_case期望输出:
toCamelCase我的代码:
def to_camel_case(text):
lst =['_', '-']
if text is None:
return ''
else:
for char in text:
if text in lst:
text = text.replace(char, '').title()
return text问题: 1)输入可以是空字符串--上面的代码不返回'‘,但没有返回;2)我不确定title()方法能否帮助我获得所需的输出(除了第一个字符之外,只有'-’或'_‘大写之前的第一个字母。
如果可能的话,我不喜欢使用regex。
发布于 2017-05-16 13:43:37
更好的方法是使用列表理解。for循环的问题是,当您从文本中删除字符时,循环会发生变化(因为应该对循环中的每个项进行迭代)。替换_或-后的下一个字母也很难大写,因为您对前后的内容没有任何上下文。
def to_camel_case(text):
# Split also removes the characters
# Start by converting - to _, then splitting on _
l = text.replace('-','_').split('_')
# No text left after splitting
if not len(l):
return ""
# Break the list into two parts
first = l[0]
rest = l[1:]
return first + ''.join(word.capitalize() for word in rest)我们的结果是:
print to_camel_case("hello-world")给出helloWorld
这种方法非常灵活,甚至可以处理像"hello_world-how_are--you--"这样的情况,如果您是新手,使用regex可能会很困难。
https://stackoverflow.com/questions/44002960
复制相似问题