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:
{"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])
CodePudding user response:
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