Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove multiple values from a tuple in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading