How to reading .txt file and rewriting by adding space after specific position / index for each line in python

前端 未结 2 1578
感动是毒
感动是毒 2021-01-27 06:32

I want to read .txt file and add space after a specific position/index for each line. please consider below example for more details.

suppose my file contains

2条回答
  •  猫巷女王i
    2021-01-27 07:36

    Here is another solution using generator expressions.

    If you are happy to provide the list of indices after each space rather than before, this will do the job:

    line = '12345 678 91011 12 1314'
    idx = [3, 7, 12, 22]
    ' '.join([line[i:j] for i, j in zip([None]+idx, idx+[None])])
    

    which gives '123 45 6 78 91 011 12 131 4'.

    Otherwise you would need to first add one to each index:

    idx = [2, 6, 11, 21]
    idx = [i+1 for i in idx]
    

提交回复
热议问题