1

I want, when i for loop, there will be comma in the end of each item except the last item, last item should be dot

x = ['df', 'second', 'something', 'another']

separator = ''
for i in x:

  r = i
  print(r, separator)
  separator = ','
else:
  separator = '.'

this is my current code.

My expected result should be like this below:

df,
second ,
something ,
another.

can anyone help me in this case?

3
  • 1
    Why not , after df? Can you explain detail rules? Commented Mar 18, 2020 at 13:11
  • 1
    should in df too, sorry Commented Mar 18, 2020 at 13:12
  • Would you check all answers and choose one of them to resolve? Commented Mar 18, 2020 at 13:26

3 Answers 3

1

Using enumerate

Ex:

x = ['df', 'second', 'something', 'another']
l = len(x)-1
for i, v in enumerate(x):
    if i != l:
        print(v, ",")
    else:
        print(v.strip()+".")

Output:

df ,
second ,
something ,
another.

or if you want it in a single line comma seperated use

print(", ".join(x) + ".") # -->df, second, something, another.
Sign up to request clarification or add additional context in comments.

Comments

0

use end in print.

x = ['df', 'second', 'something', 'another']

separator = ''
for i in x:

    r = i
    if r != x[-1]:
        print(r, end=',\n')
    else:
        print(r, end='.')

Comments

0

There are some options for you.

Output:

df,
second,
something,
another.

Simplest version:

x = ['df', 'second', 'something', 'another']

print(*x, sep=',\n', end='.')

Using str.join

print(',\n'.join(x) + '.')

Using slicing

for i in x[:-1]:
    print(f'{i},')
print(f'{x[-1]}.')

Using unpacking

*rest, last = x
for i in rest:
    print(f'{i},')
print(f'{last}.')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.