试图用Python代码破坏CamelCase实例-问题



我是初学编程的人,希望你能给我一些建议。尝试创建代码来打破CamelCase的实例-例如,gottaRunToTheStore, helloWorld等,并在输入字符串的主要单词之间添加空格。

所以我下面的代码接受一个字符串输入,应该分隔内部的单词,返回一个新的字符串,在CamelCase实例之间有空格。(所以"breakCamelCase"应该返回"break Camel case">

def solution(s):
ltstring = s              # assign input string 's' to ltstring, so if there's no CamelCase, we'll just return this string at end
Camel = []
for i in range(len(s)):        # for every character in string 's', identifying index where Camel Case occurs, adding it to list "Camel"
j = i+1                    # prepping to not do last one
if (j) < len(s):           # as long as next character index is still within string 's'
if s[j].isupper():          # if that next character in 's' is uppercase
Camel.append(j)         # add index for that CamelCase instance to list Camel
else:
pass
else:
pass
new_list = []                  # list for strings of separated 's' at CamelCase's
if Camel == []:                # if nothing was added to "Camel" return original string - line 26
pass
else:
for i in range((len(Camel)+1)):       # if there's CamelCase instances, add ind. words to a new_list
if i == 0:                          # if this is the first instance,
new_list += [s[0:Camel[0]]]         # add string from first character to character before CamelCase
last_one = len(Camel) - 1           # integer value of index for last Camel Case location
if i == len(Camel):                     # if this is last instance,
new_list += [s[Camel[last_one]:]]       # add string from last character onwards
else:                                       # otherwise
new_list += [s[Camel[i-1]:Camel[i]]]       # add string from previous char. index to current char. index
ltstring = " ".join(new_list)
return ltstring

然而,当我在这段代码上运行测试时,我在第一个CamelCase实例之后收到了一个额外的空间,而应该只有一个空间。但是下面的实例很好,只是第一个是双空格。以下是示例输出:

print(solution("breakCamelCase"))
print(solution("eatingChickenSandwichToday"))
"break  Camel Case"
"eating  Chicken Sandwich Today"

我感谢任何人在这方面的帮助!我觉得我遗漏了一个小语法问题或一些小问题,我不确定。

修改第二个for循环中的if-else语句:

def solution(s):
ltstring = s              
Camel = []
for i in range(len(s)):        
j = i+1                   
if (j) < len(s):           
if s[j].isupper():         
Camel.append(j)         
else:
pass
else:
pass
new_list = []                  
if Camel == []:                
pass
else:
for i in range((len(Camel)+1)):   
last_one = len(Camel) - 1     
if i == 0:                          
new_list += [s[0:Camel[0]]]         
# Modified if into elif         
elif i == len(Camel):                     
new_list += [s[Camel[last_one]:]]       
else:                                       
new_list += [s[Camel[i-1]:Camel[i]]]       
ltstring = " ".join(new_list)
return ltstring

输出:

print(solution("breakCamelCase"))
print(solution("eatingChickenSandwichToday"))
>>> break Camel Case
>>> eating Chicken Sandwich Today

添加一行以删除多余的空格:

new_list = list(filter(None, new_list))
ltstring = " ".join(new_list)

在这里你可以找到其他方法

相关内容

  • 没有找到相关文章

最新更新