Print out results found in Python for statement at once

Asked 2 years ago, Updated 2 years ago, 19 views

It could be a basic question. I'm asking you a question because I can't solve it by myself.

If you run the code below: Output of a values specified in the for statement

l 123 l
l 45 l
l 2 l
l 123 l
l 45 l
l 2 l
l 435 l
l 234 l
l 54 l

Finally returned a value output

end 54 end

It's printed the same way it is. L and end are letters that I put in to make sure that they are printed in the way I want them to be.

I want to receive all the values of a designated as a for statement and print them out. Based on the above results,

end 123
45
2
123
45
2
435
234
54  end

I would like to print the asd(aaa) value as above.

I don't want to print one by one, but I want to print all the values in one print command without writing a list.

What can I do?

import random
def asd(aaa):

    for i in range(random.randrange(2,9)):
        a = aaa[i]
        print('l', a, 'l')

    return a
aaa = [123, 45, 2, 435, 234, 54, 3151, 345, 1235, 123, 5, 123, 51, 35, 123, 5, 13, 5]
asd(aaa)
print('end', asd(aaa), 'end')

python

2022-09-20 19:21

1 Answers

You can use join.

>>> aaa = [123, 45, 2, 435, 234, 54, 3151, 345, 1235, 123, 5, 123, 51, 35, 123, 5, 13, 5]
>>> aaa_str = list(map(str, aaa))
>>> aaa_str
['123', '45', '2', '435', '234', '54', '3151', '345', '1235', '123', '5', '123', '51', '35', '123', '5', '13', '5']
>>> joined = '\n'.join(aaa_str)
>>> joined
'123\n45\n2\n435\n234\n54\n3151\n345\n1235\n123\n5\n123\n51\n35\n123\n5\n13\n5'
>>> print(joined)
123
45
2
435
234
54
3151
345
1235
123
5
123
51
35
123
5
13
5
>>> print(f'end : {joined} : end')
end : 123
45
2
435
234
54
3151
345
1235
123
5
123
51
35
123
5
13
5 : end


2022-09-20 19:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.