2017-10-05 74 views
0

我想從字符串中獲取特定的行列元素。如何從python中的字符串獲取特定的行列元素?

import subprocess 
process = subprocess.Popen(['free','-m'],stdout=subprocess.PIPE) 
out, err = process.communicate() 
out = out.decode("utf-8") 
print(out) 

輸出是:

   total  used  free  shared buff/cache available 
Mem:   3854  2778   299   351   776   407 
Swap:   3909   80  3829 

我想第三排,3ND列元素,也就是80 我怎樣才能得到呢?

+1

分上線,然後分割線,挑3元 –

回答

1

解碼一次,根據線分割,然後挑有趣線,採用str.split分裂並挑選相關領域。轉換爲整數

output = """    total  used  free  shared buff/cache available 
Mem:   3854  2778   299   351   776   407 
Swap:   3909   80  3829""" 

print(int(output.splitlines()[2].split()[2])) 

,讓80預期

+0

謝謝,這幫助了我。 –

相關問題