每20个字符后添加换行符并将结果保存为新字符串
我有一个字符串变量input = "A very very long string from user input",如何遍历字符串并n在 20 个字符后添加换行符,然后将格式化的字符串保存在变量中new_input?
到目前为止,我只能获得前 20 个字符,input[0:20]但是您如何通过整个字符串执行此操作并在该点添加换行符?
回答
你可能想做这样的事情
inp = "A very very long string from user input"
new_input = ""
for i, letter in enumerate(inp):
if i % 20 == 0:
new_input += 'n'
new_input += letter
# this is just because at the beginning too a `n` character gets added
new_input = new_input[1:]