簡體   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