For example, I have a list of strings:
str_list =['one', 'two', 'three', 'four', 'five']
I want to print all of them on the screen with:
for c in str_list:
print c
print ', ' # word separator
which results in:
one, two, three, four, five,
Here, a comma is not necessary at the end of the line and I don't want to print it. How can I modify the code above not to print the last comma?
It can be solved with enumerate
:
for idx, c in enumerate(str_list):
print c
if idx < len(str_list) - 1:
print ','
However, I think there may be a more elegant way to handle this.
Edited:
Maybe I thought I gave a too simple example. Suppose what if I should call function x()
for each iteration except for the last one:
for idx, x in enumerate(list_x):
if idx < len(list_x) - 1:
something_right(x)
else:
something_wrong(x)
Inside of ', '.join(['one', 'two', 'three', 'four', 'five'])
there's some sort of iteration ;)
And this is actually the most elegant way.
Here's another one:
# Everything except the last element
for x in a[:-1]:
print(x + ', ', end='')
# And the last element
print(a[-1])
Outputs one, two, three, four, five
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With