忽略pythonstring中的制表符和空格
我需要比较Python中的两个string,第一个string是从.xlsx文件读取,第二个是从stdout.readlines()的输出。
下面的代码是获取命令输出。
stdin, stdout, stderr = client.exec_command(testCommand) op = stdout.readlines() print("op =\n"+str(op)) str1 = "".join(op)
由于一些命令输出以\ t开始,或者可能在\ t之间。
例如:下面的命令输出以\ t开头,在LEN之后有\ t。
# PASS_MIN_LEN Minimum acceptable password length. PASS_MIN_LEN 5
和xlsx文件是有的
# PASS_MIN_LEN Minimum acceptable password length. PASS_MIN_LEN 5
由于.xlsx比较string没有\ t,所以如何在比较两个string时忽略\ t。
if cmdOutput== xlsxOutput:
不pipe用。
我试图用\ t修剪cmdOutput,它没有奏效。 我可以采取任何方法吗?
如果你只是想用一个空格replace标签,也许str.replace
很简单。 但是,这不会留下尾随的换行符。 你可以考虑用str.strip
replace。 例如:
op = [x.replace('\t', ' ').strip() for x in op] print(op) ['# PASS_MIN_LEN Minimum acceptable password length.', 'PASS_MIN_LEN 5']
如果您还有其他types的字符或多个字符(缺less数据等),则可以考虑使用regex更积极的方法:
import re op = [x for x in map(lambda x: re.sub('\s+', ' ', x).strip(), op)] print(op) ['# PASS_MIN_LEN Minimum acceptable password length.', 'PASS_MIN_LEN 5']
您可以使用空格replace命令输出string中的选项卡。
例如:
cmdOutput.replace('\t', ' ') == xlsxOutput
在官方的python文档中阅读strip()方法的描述。
“返回删除了前导字符和尾随字符的string副本。”
所以string中的字符保持不变。 使用replace()方法是解决您的问题的最佳scheme。
>>> str1 = "PASS_MIN_LEN\t5" >>> str2 = "PASS_MIN_LEN 5" >>> str1.replace('\t', ' ') == str2 True