Skip to content
Advertisement

How can I embed a quote inside an f-string?

I’m currently conducting a PR review and came across this:

        value = ""
        for i in uuids:
            value = value + "'" + i + "'" + ","
        where_clause = field + " IN (" + value.rstrip(",") + ")"

Nothing particularly wrong with it but I figure it can be improved using f-strings, join() and a list comprehension. However it requires me to embed some quotes in my f-string expression and I can’t figure out how to do it.

Here’s a little explainer. I can run this:

uuids = ["a", "b", "c"]
field = "myfield"
where_clause = f"{field} IN ({', '.join([i for i in uuids])})"
where_clause

which returns:

‘myfield IN (a, b, c)’

but that isn’t what’s required. What is required is to return this:

‘myfield IN (“a”, “b”, “c”)’

I’ve been fiddling around with nested f-strings, chr() & escape characters for about 10 minutes but escape characters fell foul of SyntaxError: f-string expression part cannot include a backslash and I couldn’t figure out the correct incantations to make chr() work.

If anyone can figure out how to do this I’d be very grateful.

Advertisement

Answer

Actually, this works pretty well, and is “good enough” in this case

uuids = ["a", "b", "c"]
field = "myfield"
where_clause = f"{field} IN (" +  (', '.join([f'"{i}"' for i in uuids])) + ")"
where_clause
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement