Python:字符串转驼峰命名法

Dev*_*ami 9 python string

这是来自 Codewars 的问题:完成方法/函数,以便将破折号/下划线分隔的单词转换为驼峰式大小写。仅当原始单词大写时,输出中的第一个单词才应大写(称为大驼峰式命名法,也通常称为帕斯卡大小写)。

输入测试用例如下:

test.describe("Testing function to_camel_case")
test.it("Basic tests")
test.assert_equals(to_camel_case(''), '', "An empty string was provided but not returned")
test.assert_equals(to_camel_case("the_stealth_warrior"), "theStealthWarrior", "to_camel_case('the_stealth_warrior') did not return correct value")
test.assert_equals(to_camel_case("The-Stealth-Warrior"), "TheStealthWarrior", "to_camel_case('The-Stealth-Warrior') did not return correct value")
test.assert_equals(to_camel_case("A-B-C"), "ABC", "to_camel_case('A-B-C') did not return correct value")
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试过的:

def to_camel_case(text):
    str=text
    str=str.replace(' ','')
    for i in str:
        if ( str[i] == '-'):
            str[i]=str.replace('-','')
            str[i+1].toUpperCase()
        elif ( str[i] == '_'):
            str[i]=str.replace('-','')
            str[i+1].toUpperCase()
    return str
Run Code Online (Sandbox Code Playgroud)

它通过了前两个测试,但没有通过主要测试:

 test.assert_equals(to_camel_case("the_stealth_warrior"), "theStealthWarrior", "to_camel_case('the_stealth_warrior') did not return correct value")
    test.assert_equals(to_camel_case("The-Stealth-Warrior"), "TheStealthWarrior", "to_camel_case('The-Stealth-Warrior') did not return correct value")
    test.assert_equals(to_camel_case("A-B-C"), "ABC", "to_camel_case('A-B-C') did not return correct value")
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Jos*_*osh 19

正如您的评论中提到的,您的实施可能存在一些轻微错误,但我建议您:

  • 按分隔符分割

  • 对除第一个标记之外的所有标记应用大写

  • 重新加入令牌

我的实现是:

def to_camel_case(text):
    s = text.replace("-", " ").replace("_", " ")
    s = s.split()
    if len(text) == 0:
        return text
    return s[0] + ''.join(i.capitalize() for i in s[1:])
Run Code Online (Sandbox Code Playgroud)

IMO 这更有意义。运行测试的输出是:

>>> to_camel_case("the_stealth_warrior")
'theStealthWarrior'
>>> to_camel_case("The-Stealth-Warrior")
'TheStealthWarrior'
>>> to_camel_case("A-B-C")
'ABC'
Run Code Online (Sandbox Code Playgroud)


ll2*_*2ll 7

from re import sub

def to_camelcase(s):
  s = sub(r"(_|-)+", " ", s).title().replace(" ", "").replace("*","")
  return ''.join([s[0].lower(), s[1:]])

print(to_camelcase('some_string_with_underscore'))
print(to_camelcase('Some string with Spaces'))
print(to_camelcase('some-string-with-dashes'))
print(to_camelcase('some string-with dashes_underscores and spaces'))
print(to_camelcase('some*string*with*asterisks'))
Run Code Online (Sandbox Code Playgroud)