我将字符串包装为给定的width,但是我的代码未生成预期的输出。您能帮我发现错误吗?

i=0
def wrap(string, max_width):        # function for providing string and max_width 
    for i in range(0,len(string)):   
        print(string[i:i+max_width])     
        i=i+max_width               # incrementing 'i' as per the max_width added by the user.

上面的代码o / p:

input : 'vivek'
output: 'vi'
        'iv'
        've'
        'ek'
        'k'

正确的O / P:

'vi'
've'
'k'
评论
  • 米唐
    米唐 回复

    You cannot increment the variable you use in a for loop like that, because they are overwritten in the next iteration. Either:

    1. Use a while loop, or
    2. Have range increment the variable by max_width: range(0,len(string),max_width)