3 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
我想出了以下解決方案:
您遍歷字符串,但不是在出現(xiàn)下劃線時(shí)立即用下劃線替換空格,而是存儲(chǔ)遇到的空格數(shù)。然后,一旦達(dá)到非空格字符,就將找到的空格數(shù)量添加到字符串中。因此,如果字符串以大量空格結(jié)尾,它將永遠(yuǎn)不會(huì)到達(dá)非空格字符,因此永遠(yuǎn)不會(huì)添加下劃線。
為了在開頭截掉空格,我只是添加了一個(gè)條件來添加下劃線:“我以前遇到過非空格字符嗎?”
這是代碼:
text = " I love python e "
out = ""
string_started = False
underscores_to_add = 0
for c in text:
if c == " ":
underscores_to_add += 1
else:
if string_started:
out += "_" * underscores_to_add
underscores_to_add = 0
string_started = True
out += c
print(out) # prints "I_love___python____e"

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以使用以下技巧刪除字符串中的前導(dǎo)和尾隨空格:
s = ' I love python '
ind1 = min(len(s) if c == ' ' else n for n, c in enumerate(s))
ind2 = max(0 if c == ' ' else n for n, c in enumerate(s))
s = ''.join('_' if c == ' ' else c for c in s[ind1:ind2 + 1])
print('*', s, '*', sep='')
輸出:
*I_love_python*

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
如果不允許使用 strip() 方法
def find(text):
for i, s in enumerate(text):
if s != " ":
break
return i
text = " I love python e "
text[find(text):len(text)-find(text[::-1])].replace(" ","_")
texts = [" I love python e ","I love python e"," I love python e","I love python e ", "I love python e"]
for text in texts:
print (text[find(text):len(text)-find(text[::-1])].replace(" ","_"))
輸出:
I_love___python____e
I_love___python____e
I_love___python____e
I_love___python____e
I_love___python____e
給定一個(gè)字符串
find
會(huì)找到字符串中的第一個(gè)非空格字符使用
find
查找第一個(gè)非空格字符和最后一個(gè)非空格字符使用上面找到的索引獲取子字符串
用 _ 替換上面子字符串中的所有空格
添加回答
舉報(bào)