首页 > 解决方案 > Python:字符串到 CamelCase

问题描述

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

输入测试用例如下:

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")

这是我迄今为止尝试过的:

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

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

 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")

我究竟做错了什么?

标签: pythonstring

解决方案


如您的评论中提到的,您可能有一个带有轻微错误的有效实现,但我建议您:

  • 由分隔符分割

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

  • 重新加入令牌

我的实现是:

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:])

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

>>> to_camel_case("the_stealth_warrior")
'theStealthWarrior'
>>> to_camel_case("The-Stealth-Warrior")
'TheStealthWarrior'
>>> to_camel_case("A-B-C")
'ABC'

推荐阅读