0

The input I have is a large strain of characters in a .TXT file (over 18,000 characters) and I need to add a space after every two characters. How can I write the code to provide the output in a .TXT file again?
Like so;

  • Input:
 123456789 
  • Output:
 12 34 56 78 9
Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39

3 Answers3

2

The enumerate() function is going to be doing the heavy work for you here, all we need to do is iterate over the string of characters and use modulo to split ever two characters, a worked example is below!

string_of_chars = "123456789101213141516171819"
spaced_chars = ""

for i, c in enumerate(string_of_chars):
  if i % 2 == 1:
    spaced_chars += c + " "
  else:
    spaced_chars += c

print(spaced_chars)
thisischuck
  • 153
  • 1
  • 7
2

This will produce 12 34 56 78 9

t = '123456789'
' '.join(t[i:i+2] for i in range(0, len(t), 2))

If the file is very large, you won't want to read it all into memory, and instead read a block of characters, and write them to an output handle, and loop that.

To include read/write:

write_handle = open('./output.txt', 'w')

with open('./input.txt') as read_handle:
    for line in read_handle:
        write_handle.write(' '.join(line[i:i+2] for i in range(0, len(line), 2)))

write_handle.close()
mike.k
  • 3,277
  • 1
  • 12
  • 18
1

Try the following

txt = '123456789'
print(*[txt[x:x+2] for x in range(0, len(txt), 2)])

output

'12 34 56 78 9'
Shijith
  • 4,602
  • 2
  • 20
  • 34
Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
  • My bad thanks a lot @Shijith I didn't realize that I'm missing quotes – Umutambyi Gad Oct 18 '20 at 16:15
  • Note that this relies on the `sep` argument of the `print` function but OP is not interested in printing, rather than writing to a file and `file.write(*[txt[x:x+2] for x in range(0, len(txt), 2)])` will not work... – Tomerikoo Oct 18 '20 at 16:16