繁体   English   中英

如何在python中打印以逗号分隔的单行匹配值

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

我想在单行中获取所有“主机名匹配项”的输出

#!/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=',')

我在行中打印了多个匹配项。 如何将它们用逗号分隔在一行中打印?

很简单! value = Y.split('|')[1]将为您提供匹配列表,然后选择第二个。

我们想要的是列表,因此删除[1]

现在,打印功能:

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

objects之前的*表示您可以根据需要输入任意数量的参数,例如

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

但是,如果要将列表转换为这些多个参数,则必须在前面加上*

最后,它给了我们

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

sep=的含义是它指定要在两个值之间放置的内容。

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

要指定使用其他行终止符,请改为使用end=',' 但是,实际上,收集和打印这些值的正确方法可能只是将它们收集到列表中,并在完成后打印列表。

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

您正在读取的行包含特殊字符,可能是“ \\ r \\ n”字符,即回车符和换行符。

您可以在分割行之前使用strip()方法,最后删除“ \\ r \\ n”。 另外,您需要在打印方法中使用end =“”参数。

使用以下示例:

from __future__ import print_function

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

以下是您的评论的编辑部分::

在循环打印输出时,将其存储到变量不是一个好主意,而是可以使用列表存储值,并且如果需要,可以从该列表中制作单个字符串变量。 看我下面的例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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