简体   繁体   中英

How to print in python the values which match in a single line with comma separated

I want to get the output of all the "hostname matches in single line

#!/usr/bin/env python

from __future__ import print_function

for Y in open("/tmp/inventory_file"):
    if 'hostX' in Y:
           value = Y.split('|')[1]
           print(value,sep=',')

I have multiple matches printing in rows. How can i print them in a single line with comma separated?

It's pretty easy! value = Y.split('|')[1] will get you a list of matches, and then pick the 2nd one.

What we want is the list, so remove the [1] .

Now, the print function:

print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)

The * before objects , means you can put as many arguments as you want, like

print('hello', 'pal', sep=' ')

But if you want to transform a list to those multiple arguments, you have to put an * before.

So in the end, it gives us

value = Y.split('|')
print(*value,sep=',')

The meaning of sep= is that it specifies what to put between two values.

>>> print('moo', 'bar', sep=',')
moo,bar

To specify to use a different line terminator, you want end=',' instead. But really, the proper way to collect and print these values is probably just to collect them into a list, and print the list when you are done.

values = []
for Y in open("/tmp/inventory_file"):
    if 'hostX' in Y:
           values.append(Y.split('|')[1])
print(','.join(values))

The line you are readling contains special charactors may be "\\r\\n" charactors ie carriage return and new line charactor.

you can use strip() method before splitting the line to remove "\\r\\n" at the end. Also you need to use end="" argument in print method.

use below example:

from __future__ import print_function

for Y in open("/tmp/inventory_file"):
    if 'hostX' in Y:
       value = Y.strip().split('|')[1]
       print(value,end=', ')

Below is edited section for your comment::

As you are printing output in a loop, so it is not a good idea to store this to a variable rather you can use a list to store values and also if needed you can make a single string variable from that list. see my below examples

from __future__ import print_function
result = []
for Y in open("/tmp/inventory_file"):
    if 'hostX' in Y:
        result.append(Y.strip().split('|')[1])

print(result)   #printing output as list
s = ", ".join(result)  #creating output as single string variable
print(s)   #printing output as string variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM