Python:字符串到CamelCase

2024-05-13 05:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是Codewars的一个问题: 完成该方法/函数,以便将破折号/下划线分隔的单词转换为驼峰大小写。只有当原始单词大写时,输出中的第一个单词才应大写(称为大写驼峰字母,也通常称为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")

我做错了什么


Tags: thetotestreturnvaluenotassertcase
3条回答

我认为首先应该稍微修改一下语法,因为“I”是字符串而不是整数。应该是

for i in str:
    if (i == '-'):
    ...
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'))

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

  • 按分隔符拆分

  • 对除第一个代币外的所有代币应用大写字母

  • 重新加入代币

我的实施是:

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

在我看来,这更有意义。 运行测试的输出为:

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

相关问题 更多 >