Python返回if语句



不清楚如何正确构建以下函数:

创建一个函数,该函数将接收一个字符串,并以不带空格的驼色大小写返回字符串(如果第一个字母已经是大写,则为帕斯卡大小写(,删除特殊字符

text = "This-is_my_test_string,to-capitalize"
def to_camel_case(text):
# Return 1st letter of text + all letters after
return text[:1] + text.title()[1:].replace(i" ") if not i.isdigit()
# Output should be "ThisIsMyTestStringToCapitalize"

";如果";结尾的语句不起作用,我写这篇文章有点实验性,但通过语法修复,逻辑能起作用吗?

如果输入字符串不包含任何空格,则可以执行以下操作:

from re import sub
def to_camel_case(text, pascal=False):
r = sub(r'[^a-zA-Z0-9]', ' ', text).title().replace(' ', '')
return r if pascal else r[0].lower() + r[1:]
ts = 'This-is_my_test_string,to-capitalize'
print(to_camel_case(ts, pascal=True))
print(to_camel_case(ts))

输出:

ThisIsMyTestStringToCapitalize
thisIsMyTestStringToCapitalize

这里有一个使用regex的简短解决方案。首先,它像您所做的那样使用title((,然后regex查找非字母数字字符并将其删除,最后我们使用第一个字符来处理pascal/cocamel大小写。

import re
def to_camel_case(s):
s1 = re.sub('[^a-zA-Z0-9]+', '', s.title())
return s[0] + s1[1:]
text = "this-is2_my_test_string,to-capitalize"
print(to_camel_case(text)) # ThisIsMyTestStringToCapitalize

以下内容应该适用于您的示例。

用任何非字母数字或空格分隔示例。然后将每个单词大写。最后,返回重新连接的字符串。

import re

def to_camel_case(text):
words = re.split(r'[^a-zA-Z0-9s]', text)
return "".join([word.capitalize() for word in words])
text_to_camelcase = "This-is_my_test_string,to-capitalize"
print(to_camel_case(text_to_camelcase))

使用split函数在非字母或空格的任何内容之间进行拆分,并使用.capitalize((函数将单个单词大写

import re
text_to_camelcase = "This-is_my_test_string,to-capitalize"
def to_camel_case(text):
split_text = re.split(r'[^a-zA-Z0-9s]', text)
cap_string = ''
for word in split_text:
cap_word = word.capitalize()
cap_string += cap_word
return cap_string

print(to_camel_case(text_to_camelcase))

最新更新