我正在嘗試遍歷一個字串并將下劃線轉換為駝峰式大小寫。示例)my_string --> myString
我在下面發布了我的作業代碼。有人可以幫我找出我的邏輯漏洞嗎?
def to_camel_ca (string):
camel_string = ""
for i in range(len(string)):
if string[i] == '_':
camel_string = camel_string string[i 1].replace(string[i 1], string[i 1].capitalize())
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
to_camel_ca('my_string')
#returns
m
my
myS
mySs
mySst
mySstr
mySstri
mySstrin
mySstring
'mySstring'
非常感謝!
uj5u.com熱心網友回復:
請注意,camelCase 字串會更短。當你遇到下劃線,并且將下一個字母大寫時,你需要跳過源字串中的一個字母。這是一種方法:
def to_camel_ca (string):
camel_string = ""
skip = False
for i in range(len(string)):
if skip:
skip = False
continue
if string[i] == '_':
camel_string = camel_string string[i 1].replace(string[i 1], string[i 1].capitalize())
skip = True
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
例子
to_camel_ca('my_test_string')
m my myT myTe myTes myTest myTestS myTestSt myTestStr myTestStri myTestStrin myTestString
略有不同的方法
這是一個稍微簡單的方法。遇到下劃線時,記下下一個字母大寫。它具有處理以下劃線結尾的輸入字串的優點。
def to_camel_ca (string):
camel_string = ""
capitalize = False
for i in range(len(string)):
if string[i] == '_':
capitalize = True
continue
elif capitalize:
camel_string = camel_string string[i].capitalize()
capitalize = False
elif string[i] != "_":
camel_string = camel_string string[i]
print(camel_string)
return camel_string
uj5u.com熱心網友回復:
問題是下劃線后的字符被處理/添加到 camelString 兩次:一次是在 findif和下劃線時,另一次是在該字符本身與 elif 條件匹配時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411290.html
標籤:
