Home > Software engineering >  How to limit string printing in a python loop?
How to limit string printing in a python loop?

Time:12-11

I want to make a program that will print out the next line after printing first 5 element. Example :

a = ("200","qwdecf",'acfsdvwvg','dfwrvgrwb','fwrfw','fwfw','wefweg53',"1233",'2344','09845')

Output

"200","qwdecf",'acfsdvwvg','dfwrvgrwb','fwrfw'
'fwfw','wefweg53',"1233",'2344','09845'

Most of them I found was using integers, not strings.. So I'm a little stuck. Thanks for helping.

This is my code now:

line = 0
for i in range(len(a)):
    line =1
    print(a[:6])

CodePudding user response:

Maybe do something like this:

a = (0, 2, "3'", True, 2, "c", 'f')
max_word_count = 5
output = ""

for i, j in enumerate(a):
    if i % max_word_count == 0:
        output  = "\n"

    output  = f"{str(j)} "

CodePudding user response:

This works as you specified in the question:

a = ("200","qwdecf",'acfsdvwvg','dfwrvgrwb','fwrfw','fwfw','wefweg53',"1233",'2344','09845')
next_line=1
output=""
for i in range( len(a) ):
    output ='\"' a[i] '\"'
    if next_line == 5:
        output = "\n"
        next_line=0
    else:
        output =","
    next_line =1
print(output)

Output:

"200","qwdecf","acfsdvwvg","dfwrvgrwb","fwrfw"
"fwfw","wefweg53","1233","2344","09845"

CodePudding user response:

Same answer as CozyCode - However juste note that in

a = ("200","qwdecf",'acfsdvwvg','dfwrvgrwb','fwrfw','fwfw','wefweg53',"1233",'2344','09845')

for key, value in enumerate(a):
    if (key   1) % 5 == 0:
        print(value)
    else:
        print(value, end =" ") 

enumerate(a) returns an iterable where each of your initial values are paired with their own index. That's why you can use for key, value in ..

  • Related