printing double quotes around a variable

前端 未结 7 1369
闹比i
闹比i 2020-11-29 11:50

For instance, we have:

word = \'Some Random Word\'
print \'\"\' + word + \'\"\'

is there a better way to print double quotes around a varia

7条回答
  •  有刺的猬
    2020-11-29 12:44

    How about json.dumps:

    >>> import json
    >>> print(json.dumps("hello world"))
    "hello world"
    

    The advantage over other approaches mentioned here is that it escapes quotes inside the string as well (take that str.format!), always uses double quotes and is actually intended for reliable serialization (take that repr()!):

    >>> print(json.dumps('hello "world"!'))
    "hello \"world\"!"
    

提交回复
热议问题