Python,拆分字符串

时间:2011-02-03 04:01:14

标签: python string split

我有一个大的字符串文本文件,我想每117个字符拆分字符串,然后将下一个117个字符放在换行符上,依此类推,直到文件结束。

我试过这个:`s =“”“ 我出于可见性原因删除了字符串 “”” space =“”“

“”” file = open('testoutput.txt','w') 而s:     print s [:10]     output = output + s +“”“

"""
s = s[10:]

file.write(输出) file.close() 打印“完成” `

但问题是文件中的最终输出看起来像这样的级联:`[this [SHIFT] r [BACKSPACE]分子及其后代av [BACKSPACE] [BACKSPACE]因突变而变化

T]r[BACKSPACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ACE]molecule and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



le and its descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



 descendants would av[BACKSPACE][BACKSPACE]vary because of mutations



ts would av[BACKSPACE][BACKSPACE]vary because of mutations



v[BACKSPACE][BACKSPACE]vary because of mutations



E][BACKSPACE]vary because of mutations



CE]vary because of mutations



cause of mutations



utations

`

2 个答案:

答案 0 :(得分:6)

while s:
    print s[:117]
    s = s[117:]

答案 1 :(得分:3)

您可以使用常规切片语法拆分缓冲区,也可以选择在读取文件时直接拆分文件。这是第二种方法的一个例子:

with open(r"/path/to/some/file") as input_file:
    line = input_file.read(117)
    while line:
        print len(line)
        line = input_file.read(117)