0

I have an issue transforming my current variable(which is a dictionary) into a literal string. I have a dictionary variable such as :

tmp = {"e":"abc' efg"}

And I want to convert tmp into a string, such as

'''{"e":"abc' efg"}'''

However, when I use str(tmp), I get

'{\'e\': "abc\' efg"}'

which I do not want to have escape symbol for the string.

How would I get a value such that

'''{"e":"abc' efg"}'''

In another word, I am looking forward an operation(op) such that

op(tmp)==tmp1 is true, where tmp = {"e":"abc' efg"}, tmp1='''{"e":"abc' efg"}''' .

Lala James
  • 33
  • 4
  • 3
    Are all of your values JSON-serializable? How about `json.dumps(tmp)`? – ggorlen Aug 21 '20 at 22:30
  • 2
    The backslashes aren't actually in the string, they're just how a string containing backslashes is displayed. – Barmar Aug 21 '20 at 22:33
  • 1
    If you do `print(str(tmp))` you won't see the backslashes. – Barmar Aug 21 '20 at 22:34
  • @ggorlen Thanks a lot! This is what I am looking for. By the way, Suppose tmp = {"e":"abc' efg"} tmp1 = '''{"e":"abc' efg"}''' What is the operation on tmp so that op(tmp)==tmp1 is True? Currently, what I have check is that str(tmp)==tmp1 or json.dumps(tmp)==tmp1 is False. – Lala James Aug 21 '20 at 22:42
  • @Barmar. Hello, Thank you for your comments. It is helping me a lot.. Actually, what I am looking for is that Suppose tmp = {"e":"abc' efg"} tmp1 = '''{"e":"abc' efg"}''' What is the operation on tmp so that op(tmp)==tmp1 is True? Currently, str(tmp)==tmp1 or json.dumps(tmp)==tmp1 is False. – Lala James Aug 21 '20 at 22:44
  • 3
    The answer is that you shouldn't use string comparisons. You should decode the string with `json.loads()` or `ast.literal_eval()` and then compare the data. – Barmar Aug 21 '20 at 22:48
  • There are too many different ways to convert data to a string, such as different amounts of whitespace. – Barmar Aug 21 '20 at 22:49
  • 1
    If you're really trying to check if two dicts are equal, stringifying them is likely not the best way to go. See: https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-and-checking-how-many-key-value-pairs-are-equal – ggorlen Aug 21 '20 at 22:49
  • @Barmar Thanks a lot. cannot make a day with your unreserved help. – Lala James Aug 21 '20 at 22:54
  • @ggorlen wish I could thank you in person. – Lala James Aug 21 '20 at 22:55

0 Answers0