I've had a similar issue when creating an xpath query from a string when we had to do so for a particular widget. What helped for us was to use triple quotes in the string, like this:
This fixed our issue and the xpath seems to be working properly. I'm not sure if this would work for your use case, but it might be worth a try.
Another thing which may work, in case Eline's answer doesn't fit your usecase, is attempting to escape the characters. This is described here: https://docs.mendix.com/refguide/string-function-calls
I've copy pasted the specific part (with Q\ and E\) below.