How to remove multiple values from a tuple in python

90 Views Asked by At

I have a tuple which is an output of a select query. The tuple looks like this:

('checkStatus id \n========================= ==================== \nfalse adcs-fddf-sdsd \n', None)

I am trying to retrieve only the two values i.e. false and adcs-fddf-sdsd

This is the code:

import subprocess

def foo():
  cmd = return ("select checkStatus , id from abc") 
  pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=TRUE)
  output = pr.communicate()
  print(output)          //('checkStatus id              \n========================= 
                         //      ==================== \nfalse adcs-fddf-sdsd \n', None)

Now, I found out that I can use replace to remove the unwanted white space using str(output).replace(' ', ''). So, for all the other details also I will have to add multiple replace statements. So, is there a better way to retrieve only those 2 values (false and adcs-fddf-sdsd) .

NOTE The code has to be compatible for both Python version 2 and 3.

2

There are 2 best solutions below

3
iFlo On BEST ANSWER

If your output is always in a similar form you could get the position of the last \n (let's call it x) and the one before that (let's call it y). You can retrieve this with "rfind" (rfind) and then split the result to get a list with false and adcs-fddf-sdsd.

output = pr.communicate()[0]
x = output.rfind('\n')
y = output.rfind('\n', 0, x)
print(output[y:x].split())
0
SABARI NATHAN G On

To retrieve only the two values "false" and "adcs-fddf-sdsd" from the output tuple of your SQL query, you can use regular expressions to parse the string. This approach allows you to extract specific patterns from the text regardless of the presence of whitespace or other formatting characters. Here's how you can modify your code to achieve this: