MrDuk
MrDuk

Reputation: 18242

How can I print each list item, in a single line of code?

I want to do something like:

print ' -- Checking connectivity from {} to {}'.format((h for h in env.hosts), (h for h in dbHostList))

However, this only produces: -- Checking connectivity from <generator object <genexpr> at 0x2c36190> to <generator object <genexpr> at 0x2c367d0>

I know there's a way to do this, and I'm just skipping something small.. but I don't know what. Any help is appreciated.

Upvotes: 0

Views: 89

Answers (4)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

If you want a line for each check, you can join newlines together with a formatted string for each pair of hosts. zip can combine the two lists so you can iterate over them pairwise:

print '\n'.join('  -- Checking connectivity from {host} to {db_host}'
                .format(host=host, db_host=db_host)
                for host, db_host in zip(env.hosts, dbHostList))

Upvotes: 0

PTBNL
PTBNL

Reputation: 6122

In general, if your list items are strings, you can use string join:

print ' '.join(env.hosts)

If your list items aren't strings, you can use a list comprehension in which you call str() (assuming you have a data type that can be converted by str()) to make them strings:

print ' '.join([str(h) for h in env.hosts])

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

Not sure how you want the lists formatted, but you could do

print '  -- Checking connectivity from {} to {}'.format(env.hosts, dbHostList)

This would create a string like

'  -- Checking connectivity from [1, 2, 3] to [4, 5, 6]'

Otherwise if you want some particular format/delimiter you could use join, for example

print '  -- Checking connectivity from {} to {}'.format(':'.join(map(str, env.hosts)), ':'.join(map(str, dbHostList)))

Which would print

'  -- Checking connectivity from 1:2:3 to 4:5:6'

Upvotes: 1

lennyklb
lennyklb

Reputation: 1367

(for object in sequence)

creates a Generator. You want this:

[for object in sequence]

edit:

Or this:

print "Stuff stuff stuff {}".format(" ".join(list))

Upvotes: 3

Related Questions