这是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")
我做错了什么
我认为首先应该稍微修改一下语法,因为“I”是字符串而不是整数。应该是
正如您在评论中提到的,您可能有一个工作实现,但有轻微错误,但我建议您:
按分隔符拆分
对除第一个代币外的所有代币应用大写字母
重新加入代币
我的实施是:
在我看来,这更有意义。 运行测试的输出为:
相关问题 更多 >
编程相关推荐