pythonstringescapingbackslash

How can I programmatically build a string containing escaped characters to pass as an argument to a function in Python?


I am trying to build the string below programatically:

string0 = 'case when \"LETTER\" in (\'a\',\'b\') then \"LETTER\" else \'other letter\' end'

I do:

a_list = ['a','b']
string = '(\\\''+'\\\',\\\''.join(a_list)+'\\\')'
string2 = 'case when \"LETTER\" in ' + string + ' then \"LETTER\" else \'other letter\' end'

however, string0 == string2 returns False


Solution

  • You can use this command:

    string = '(' + ','.join(f"'{x}'" for x in a_list) + ')'
    

    When you keep other comands from your question as they are, then string0 and string2 will be the same.

    But it is not clear, if it is what you really want.

    Some backslash characters in the string0 definition are redundant and has no meaning. For example:

    >>> test = 'case when \"LETTER\"'
    >>> print(test)
    case when "LETTER"
    
    >>> test2 = 'case when "LETTER"'
    >>> print(test2)
    case when "LETTER"
    >>> test == test2
    True