simplycoding
simplycoding

Reputation: 2967

Printing all elements of a list next to another string

I know that printing all elements of a string has been asked and answered many times, but I'm having trouble finding a solution for doing that in-line, and next to another statement.

I have the following setup:

api_endpoints = ['candidate', 'employee']

print(*api_endpoints, sep=', ')
# candidate, employee

print('Getting data for: ', *api_endpoints, sep=', ')
# Getting data for: , candidate, employee

But I would like the desired output to be: Getting data for: candidate, employee

Without altering the list, how do I print this statement like I want it to?

Upvotes: 2

Views: 206

Answers (3)

DarK_FirefoX
DarK_FirefoX

Reputation: 896

Just adding this to very valid previous answers.

Assuming you are in Python 3.6+. You can do something like this using string interpolation which I've found to be very useful.

print(f"Getting data for: {', '.join(api_endpoints)}")

Upvotes: 2

S.B
S.B

Reputation: 16476

You can either use .join() to build your string :

api_endpoints = ['candidate', 'employee']
print('Getting data for: ' + ', '.join(api_endpoints))

Or do some overkill by redirecting print() output and store it in a variable which you can then use where ever you want:

from io import StringIO
import sys

result = StringIO()

# redirect to 'result'
sys.stdout = result

api_endpoints = ['candidate', 'employee']
print(*api_endpoints, sep=', ', end='')

# reset back
sys.stdout = sys.__stdout__
print('Getting data for: ' + result.getvalue())

output :

Getting data for: candidate, employee

Upvotes: 2

Yunus
Yunus

Reputation: 1

Use as:

",".join(api_endpoints)

Upvotes: 0

Related Questions