这是一个长字符串,我将其转换为列表,以便我可以对其进行操作,然后将其重新连接在一起。我在让迭代器遍历列表时遇到了一些麻烦,当迭代器到达时,假设每第 5 个对象,它应该在那里插入一个 '\n' 。这是一个例子:
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()
# do the magic here
string = ' '.join(string)
print(string)
输出:
Hello my name is Josh
I like pizza and python
I need this string to
be really really long
知道如何实现这一目标吗?
我尝试使用:
for words in string:
if words % 5 == 0:
string.append('\n')
但它不起作用。我错过了什么?
最佳答案
您做错的事情是尝试更改示例中的string
,这不会影响列表中包含的字符串...相反,您需要索引到列表并直接更改元素。
text = "Hello my name is Josh I like pizza and python I need this string to be really really long"
words = text.split()
for wordno in range(len(words)):
if wordno and wordno % 5 == 0:
words[wordno] += '\n'
print ' '.join(words)
您不想调用 string
,因为它是一个内置模块,有时会使用并且可能会造成混淆,而且我还检查了 wordno
不是“t 0 否则你最终会在重新加入时得到一个字行...
关于python - 如何使用分割长列表\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386012/