python string adding backslash before single quotes

后端 未结 3 1600
借酒劲吻你
借酒劲吻你 2020-12-12 02:06

I have a string that contains quotes like this:

string = \"\\\"This is my mom\'s vase\\\", said Kevin.\"

Problem is when I use it as a stri

相关标签:
3条回答
  • 2020-12-12 02:49

    I found the solution, it has nothing to do with repr(string), as @Aran-Fey mentions, it has to do with API and Jsons response.

    The correct approach is that you are not returning strings or jsons dumps, but response which http protocols interprets as you mention: \" (backslaches every string).

    The solution is to make a http response as follows:

    from flask import request, jsonify, make_response
    from flask_restful import Resource
    from flask_api import status
    
    class employeeHiring(Resource):
        def post(self):
        #YOUR CODE ....
        return make_response(jsonify({'status': 'success', 'my Dict': dict}), status.HTTP_201_CREATED)
    
    0 讨论(0)
  • 2020-12-12 02:55

    It's just escaped in the REPL. If you print it out, it will show there is no slash added:

    print(string)
    # output: "This is my mom's vase", said Kevin.
    
    0 讨论(0)
  • 2020-12-12 02:56

    The Explanation

    What you're seeing is the representation of your string as produced by the repr function. repr outputs strings in such a way that they're valid python literals; in other words, you can copy/paste the output of repr(string) into a python program without getting a syntax error:

    >>> string
    '"This is my mom\'s vase", said Kevin.'
    >>> '"This is my mom\'s vase", said Kevin.'  # it's valid python code!
    '"This is my mom\'s vase", said Kevin.'
    

    Because your string contains both single quotes ' and double quotes ", python has to escape one of those quotes in order to produce a valid string literal. The same way you escaped your double quotes with backslashes:

    "\"This is my mom's vase\", said Kevin."
    

    Python instead chooses to escape the single quotes:

    '"This is my mom\'s vase", said Kevin.'
    

    Of course, both of these strings are completely identical. Those backslashes are only there for escaping purposes, they don't actually exist in the string. You can confirm this by printing the string, which outputs the string's real value:

    >>> print(string)
    "This is my mom's vase", said Kevin.
    

    The Solution

    There's nothing to solve! What are you still doing here? Scroll up and read the explanation again!

    0 讨论(0)
提交回复
热议问题