[Python] Python use double quotes in string representation

Discussão em 'Python' iniciado por Stack, Agosto 14, 2025.

  1. Stack

    Stack Membro Participativo

    In Python the str builtin gives the string representation of a value. At least for dictionaries, it gives Python code you could then evaluate to get the same value.

    >>> print(str('a'))
    a
    >>> print(str({'x':5}))
    {'x': 5}


    In Python either " or ' can be used as quote characters. Suppose I prefer ". How can I get the string representation of a value using double quotes instead? It would be something like

    >>> print(my_str('a'))
    a
    >>> print(my_str({'x':5}))
    {"x": 5}


    The output would still be valid Python as before, but it would use " in preference to '.

    I know I could output the value as JSON, which looks roughly similar to Python-with-double-quotes in many cases, but here I want to keep valid Python output, just with a stylistic difference.

    Continue reading...

Compartilhe esta Página