Python Forum

Full Version: get string how it is defined
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I can have any characters inside the string. For eg.

str = "some\" quoted value'foo"
print(str)
# some" quoted value'foo
How can I get it printed intact?
# some\" quoted value'foo
The point is that there are several ways to represent literally a string. The general idea is to use repr()
>>> s = "some \" quo\u0074ed value'foo"
>>> print(repr(s))
'some " quoted value\'foo'
You cannot be 100% sure to recover the initial form because the compiler interpretes the string and it doesn't remember that the " was initially escaped and ' was not for example, or that t was written \u0074
Ah, that doesn't help me. What I'm trying to do is combine that string in previous string. For eg.

str = "{a:"
str += "some \" quoted value'foo"
str += "}"
Which should result in:

# {a:"some \" quoted value'foo"}
# But not:
# {a:"some " quoted value\'foo"}
So, what I want is what user has inputed exactly.
Never use str as name. Otherwise you can find yourself wondering:

In [1]: str(100)                                                                
Out[1]: '100'

In [2]: str = "some\" quoted value'foo"                                         

In [3]: str(100)                                                                
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-1aa51eeeed3a> in <module>
----> 1 str(100)

TypeError: 'str' object is not callable
You need to understand that when you write
s = "some \" quoted value 'foo"
the string s doesn't contain any \ character. It means that your requirement that "it should result in" a string with a backslash character is not well defined. You'll have to write your own escaping function and implement your own rules, for example you could replace all the " in a string with \".
I may not know what user may post in their inputs. So, it's hard know what to replace. Or, is it just fine to replace all backslashes?
your post is example of classical XY problem in my view. it looks like you try to construct json string/file and doing so the wrong way.
As Griboullis explained there are subtle differences how string stored and how it's printed out:

>>> backslash = '\\'
>>> a = "{a:"
>>> a += f"some {backslash}\" quoted value'foo"
>>> a += "}"
>>> print(a)
{a:some \" quoted value'foo}
>>> a
'{a:some \\" quoted value\'foo}'
import json
foo = "some\" quoted value'foo"
spam = {'a':foo}
json_str = json.dumps(spam)
print(json_str)
Output:
{"a": "some\" quoted value'foo"}
Ah, this works just fine! Thanks. Was forgetting about dumps. How can I mark your answer as solution?
Pages: 1 2