【问题标题】:Python, splitting stringsPython,拆分字符串
【发布时间】:2011-02-03 04:01:14
【问题描述】:

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

我试过这个:`s = """ 出于可见性原因,我删除了字符串 """ 空格 = """

""" 文件=打开('testoutput.txt','w') 而小号: 打印 s[:10] 输出 = 输出 + s + """

"""
s = s[10:]

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

但是文件中的最终输出看起来像这种级联的问题:`这个 [SHIFT]r[BACKSPACE] 分子及其后代会因为突变而改变 [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

`

【问题讨论】:

    标签: python string split


    【解决方案1】:
    while s:
        print s[:117]
        s = s[117:]
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多