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

Python Remove Additional & in the end whilst generating a query string

I am constructing a query string for pandas and appending & at the end of each condition

So, for example if I have condition1, condition2, condition3 my query would be generated as: "condition1 & condition2 & condition3 &"

I am using json to provide flexibility to the user to specify condition and then read json:

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

    {"scenario": "123-456-222",  
     "query": 
        {
          "key": "field1",
          "value": "condition1"
        },
        {
          "key": "field2",
          "value": "condition2"
        },
        {
          "key": "field3",
          "value": "condition3"
        },
    "data": 

Next, I use python’s final_condition[:-1] to remove the redundant & in the end.

Wondering if there’s a better way to organise this code.

test_str = "field1=condition1 & field2=condition2 & field3=condition3 &"
print(test_str[:-1])

>Solution :

You can use str.join to put the ampersands between the operands:

args = ["statement 1", "statement 2",  "statement 3"]
output = " & ".join(args)
print(output)
# statement 1 & statement 2 & statement 3
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