thenomazion
thenomazion

Reputation: 1

Python insert comma every third character multi-line error

I am using python to try to insert a comma after every third character, and it works fine if my text file is one line, but is breaking for my multi-line text file

Input:

bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz

output:

bcd, fgh, jkl, mnp, qrs, tvw, xyz,
bc, dfg, hjk, lmn, pqr, stv, wxy, z
b, cdf, ghj, klm, npq, rst, vwx, yz
, bcd, fgh, jkl, mnp, qrs, tvw, xyz,
bc, dfg, hjk, lmn, pqr, stv, wxy, z

Desired Output:

bcd, fgh, jkl, mnp, qrs, tvw, xyz
bcd, fgh, jkl, mnp, qrs, tvw, xyz
bcd, fgh, jkl, mnp, qrs, tvw, xyz
bcd, fgh, jkl, mnp, qrs, tvw, xyz
bcd, fgh, jkl, mnp, qrs, tvw, xyz 

CODE:

with open("input.txt") as main:
    words = main.read() 

res = ', '.join(words[i:i + 3] for i in range(0, len(words), 3))

print(res)

Upvotes: 0

Views: 604

Answers (1)

LeopardShark
LeopardShark

Reputation: 4446

It’s because a newline is a character, so your program is adding a comma every three characters, that’s just not quite what you want. You can apply it to every line separately, like this:

with open("input.txt") as main:
    words = main.readlines()

res = "\n".join(
    ", ".join(line[i : i + 3] for i in range(0, len(line), 3)) for line in words
)

print(res)

Upvotes: 1

Related Questions