python - 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")
我究竟做错了什么?
解决方案
如您的评论中提到的,您可能有一个带有轻微错误的有效实现,但我建议您:
由分隔符分割
对除第一个标记之外的所有标记应用大写
重新加入令牌
我的实现是:
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'
推荐阅读
- php - 尝试更新联系人记录,但我获得执行操作的权限被拒绝 id
- c++ - 您是否使用 cv::calibrateCamera() 获得与使用 cv::fisheye::calibrate() 相同的相机矩阵结果
- python - 带有变量的字典的索引字典
- angular - InvalidValueError:在属性来源中:不是字符串;而不是 LatLng 或 LatLngLiteral:不是对象;而不是一个对象
- wpf - WPF - 文本框的 SuggestAppend
- powershell - PowerShell Remove-Item - 字符串后的通配符?
- python - sqlalchemy 可以添加两个特定列不能同时为 None 的字段级规则吗?
- mysql - 更改 apache 的端口后,mysql 在 xampp 中运行正常,但 myphpadmin 显示这些错误
- variables - 我们可以在 gitlab-ci.yml 中使用动态作业名称吗?
- c# - 从另一个窗口句柄获取实时消息