我使用python试图在每三个字符后插入一个逗号,如果我的文本文件是一行,但是正在破坏我的多行文本文件
输入:
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
bcdfghjklmnpqrstvwxyz
输出:
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
期望输出:
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
代码:
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)
这是因为换行符是一个字符,所以您的程序每三个字符添加一个逗号,这不是您想要的。您可以将其单独应用于每一行,如下所示:
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)