如何在python中从字符串中获取特定的行-列元素?
我想从字符串中获取特定的行-列元素如何在python中从字符串中获取特定的行-列元素?,python,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 ava
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
我想得到第三行,第三列元素,即80。
如何获得该值?解码后,根据行进行拆分,然后选择感兴趣的行,使用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个行拆分,然后拆分行,选择第三个元素