初學者編碼器在這里,非常感謝對此的一些見解。嘗試創建代碼來破壞 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"
我感謝任何人在這方面提供幫助!我覺得我錯過了一個小語法問題或一些小問題,我不確定。
uj5u.com熱心網友回復:
添加此行以洗掉多余的空格:
new_list = list(filter(None, new_list))
ltstring = " ".join(new_list)
而在這里,你可以找到其他方法
uj5u.com熱心網友回復:
更改第二個 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335594.html
上一篇:逐字反轉字串而不使用javascript中的內置函式
下一篇:計算二進制數中的0序列
