使用OS命令grep并将结果存入元组后,如何去除制表符 ?
Hey there! Let's tackle that tab character problem in your tuple. First, I noticed a small typo in your code—cldb.split('\n') should probably be cmd.split('\n') since cldb isn't defined anywhere. Fixing that first will get you the right data to work with.
Now, to remove those tabs, here are a few straightforward approaches:
Option 1: Replace tabs before splitting the command output
You can clean the entire command output string first by replacing all tab characters (\t) with an empty string (or a space if you prefer to keep spacing) before splitting it into lines:
args = parser.parse_args() find = args.data_variable cmd = commands.getoutput("cat /cc/ddd '"+find+"' |grep -A 3 node | tail -n +2") # Replace all tabs in the output first cleaned_cmd = cmd.replace('\t', '') r = tuple(cleaned_cmd.split('\n')) print(r)
Option 2: Clean each element in the tuple after splitting
If you only want to remove tabs from individual lines (or need more control over each line), use a list comprehension to process each line before converting to a tuple:
args = parser.parse_args() find = args.data_variable cmd = commands.getoutput("cat /cc/ddd '"+find+"' |grep -A 3 node | tail -n +2") # Process each line to strip tabs cleaned_lines = [line.replace('\t', '') for line in cmd.split('\n')] r = tuple(cleaned_lines) print(r)
If you also want to trim any leading/trailing whitespace along with tabs, you can use line.strip() instead—but note that this will remove all leading/trailing spaces too, not just tabs.
Option 3: Handle it directly in the shell command
You can even add a sed command to your pipeline to replace tabs before the output gets to Python:
args = parser.parse_args() find = args.data_variable # Add | sed 's/\t//g' to remove all tabs in the shell pipeline cmd = commands.getoutput("cat /cc/ddd '"+find+"' |grep -A 3 node | tail -n +2 | sed 's/\t//g'") r = tuple(cmd.split('\n')) print(r)
All these methods will get rid of those unwanted tab characters in your final tuple. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者learnerpy

