Python 2.7 - 从字符串中删除特殊字符并使用驼峰式大小写
Python 2.7 - remove special characters from a string and camelCasing it
输入:
to-camel-case
to_camel_case
期望输出:
toCamelCase
我的代码:
def to_camel_case(text):
lst =['_', '-']
if text is None:
return ''
else:
for char in text:
if text in lst:
text = text.replace(char, '').title()
return text
问题:
1)输入可以是一个空字符串——上面的代码不是return''而是None;
2) 我不确定 title()
方法是否可以帮助我获得所需的输出(只有每个单词的第一个字母在 '-' 或 '_' 之前的大写字母除外。
如果可能,我不想使用正则表达式。
更好的方法是使用 list comprehension。 for 循环的问题在于,当您从文本中删除字符时,循环会发生变化(因为您应该遍历循环中最初的每个项目)。替换 _
或 -
后也很难将下一个字母大写,因为您不知道前后的内容。
def to_camel_case(text):
# Split also removes the characters
# Start by converting - to _, then splitting on _
l = text.replace('-','_').split('_')
# No text left after splitting
if not len(l):
return ""
# Break the list into two parts
first = l[0]
rest = l[1:]
return first + ''.join(word.capitalize() for word in rest)
我们的结果:
print to_camel_case("hello-world")
给予helloWorld
这种方法非常灵活,甚至可以处理像 "hello_world-how_are--you--"
这样的情况,如果您是新手,使用正则表达式可能会很困难。
输入:
to-camel-case
to_camel_case
期望输出:
toCamelCase
我的代码:
def to_camel_case(text):
lst =['_', '-']
if text is None:
return ''
else:
for char in text:
if text in lst:
text = text.replace(char, '').title()
return text
问题:
1)输入可以是一个空字符串——上面的代码不是return''而是None;
2) 我不确定 title()
方法是否可以帮助我获得所需的输出(只有每个单词的第一个字母在 '-' 或 '_' 之前的大写字母除外。
如果可能,我不想使用正则表达式。
更好的方法是使用 list comprehension。 for 循环的问题在于,当您从文本中删除字符时,循环会发生变化(因为您应该遍历循环中最初的每个项目)。替换 _
或 -
后也很难将下一个字母大写,因为您不知道前后的内容。
def to_camel_case(text):
# Split also removes the characters
# Start by converting - to _, then splitting on _
l = text.replace('-','_').split('_')
# No text left after splitting
if not len(l):
return ""
# Break the list into two parts
first = l[0]
rest = l[1:]
return first + ''.join(word.capitalize() for word in rest)
我们的结果:
print to_camel_case("hello-world")
给予helloWorld
这种方法非常灵活,甚至可以处理像 "hello_world-how_are--you--"
这样的情况,如果您是新手,使用正则表达式可能会很困难。