问题描述
ws = []
和字符串:
text = "cmon lets go"
我将检查空格并将空格索引存储在 ws 数组中,然后我将有:
ws = [4,9]
然后我会有一些其他的字符串:
new_string = "cmonzletszgo"
所有空格都用字母 z 切换的地方(没关系)。 现在我想遍历 new_string 并用空格替换数组 ws 中索引中的字符,所以我想得到
new_string = "cmon lets go"
解决方法
由于您有要替换的索引,您可能想尝试迭代 res.end()
而不是 ws
:
new_string
这将用 for i in ws:
new_string = new_string[:i] + ' ' + new_string[i + 1:]
中指定的索引处的空格替换 new_string
中的字符,无论当前可能存在什么字符。
我只考虑第一部分,即单行。
ws = [i for i,ch in enumerate(text) if ch.isspace()]
我错过了第二部分的一个关键点,其意图是使用 ws 进行替换。再次,单行:
new_string = ''.join([' ' if i in ws else ch for i,ch in enumeration(new_string)])