python - 如何使用分割长列表\n

标签 python string

这是一个长字符串,我将其转换为列表,以便我可以对其进行操作,然后将其重新连接在一起。我在让迭代器遍历列表时遇到了一些麻烦,当迭代器到达时,假设每第 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/

相关文章:

c++ - 比较字符串中的符号时出现 std::out_of_range 错误

python - 列名称中存在未知字符

c++ - 从字符串中以指数表示法解析整数

python - 多对多关系中带有附加字段的 Django 管理表单

python - 将字典映射到数据框中的部分字符串匹配

java - ArrayList困惑

java - 如何将 DatePicker 值转换为字符串?

C++ 将 const char* 指针数组传递给对象

python - zip(*) 是如何生成 n-gram 的?

python - 如何在终端中打印 df 而不丢失格式?