2017-05-16 45 views
0

输入:Python 2.7版 - 从字符串中删除特殊字符和驼峰规则它

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()方法可以帮助我获得所需的输出(只有' - '之前的每个单词的第一个字母或除第一个之外的'_')。如果可能的话使用正则表达式

回答

1

更好的方法是使用list comprehension。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--",使用正则表达式,如果你是新手的话这可能是困难的。

相关问题