3 回答

TA贡献1806条经验 获得超8个赞
我想出了以下解决方案:
您遍历字符串,但不是在出现下划线时立即用下划线替换空格,而是存储遇到的空格数。然后,一旦达到非空格字符,就将找到的空格数量添加到字符串中。因此,如果字符串以大量空格结尾,它将永远不会到达非空格字符,因此永远不会添加下划线。
为了在开头截掉空格,我只是添加了一个条件来添加下划线:“我以前遇到过非空格字符吗?”
这是代码:
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贡献1796条经验 获得超10个赞
您可以使用以下技巧删除字符串中的前导和尾随空格:
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贡献1155条经验 获得超0个赞
如果不允许使用 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
给定一个字符串
find
会找到字符串中的第一个非空格字符使用
find
查找第一个非空格字符和最后一个非空格字符使用上面找到的索引获取子字符串
用 _ 替换上面子字符串中的所有空格
添加回答
举报