您的位置:首页 > 编程语言 > Python开发

Python刷题笔记(4)- 字符串重组

2015-11-19 10:32 986 查看

题目:

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.

Examples:

# returns "theStealthWarrior"
to_camel_case("the-stealth-warrior")

# returns "TheStealthWarrior"
to_camel_case("The_Stealth_Warrior")

中文简介:

其实就是去掉字符串中的‘-’或‘_‘连接符,然后除去第一个单词外,其他单词首字母大写连接

想法:

1、历遍字符串,找到单词间隔符’-‘和’_',然后通过两次循环找到首尾的间隔符,提取中间的单词,并让首字母大写

2、输入空字符串,返回空字符串

3、寻找第一个单词和最后一个单词,第一个单词通过一次历遍寻找第一个间隔符,然后跳出循环,最后一个单词通过储存最后次首间隔符的循环数,然后查找出后面的单词

实现:

def to_camel_case(text):
if text == '':
return ''
list = []
for i in range(len(text)):
if text[i] == '-' or text[i] == '_':
list.append(text[:i])
break
for i in range(len(text)):
if text[i] == '-' or text[i] == '_':
for j in range(i+1,len(text)):
if text[j] == '-' or text[j] == '_':
list.append(text[i+1].upper() + text[i+2:j])
break
k = i
list.append(text[k+1].upper() + text[k+2:])
return ''.join(list)

对比总结:

这种实现方法比较笨拙,采用耿直的思想来进行。通过测试提交后,才恍然大悟应该用split()函数来分割啊,这样就简单多了,根本不需要自己去历遍查找间隔符……通过replace()函数来替代统一间隔符,然后使用split()进行分割,立刻就能得到单词列表,然后
用capitalize()函数将
后面的单词首字母大写就行了……

def to_camel_case(text):
if text == '':
return ''
list =[string.capitalize() for string in text.replace('-','_').split('_')]
return text[0] + ''.join(list)[1:]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: