簡體   English   中英

Python,拆分字符串

[英]Python, splitting strings

我有一個大的字符串文本文件,我想每117個字符拆分字符串並將下一個117個字符放在換行符上,依此類推,直到文件結束。

我試過這個:`s =“”“我出於可見性原因刪除了字符串”“”space =“”“

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

"""
s = s[10:]

file.write(output)file.close()print“Done”`

但有一個問題,文件中的最終輸出看起來像這個級聯:`這個[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

`

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

您可以使用常規切片語法拆分緩沖區,也可以選擇在讀取文件時直接拆分文件。 這是第二種方法的一個例子:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM