write escaped character to file so that the character is visible

萝らか妹 提交于 2019-12-23 17:58:18

问题


I want to write "\t" to a file. Not a "tab character", but literally "\t". How do I do this? It has been driving me crazy for more than an hour; everything I try produces an actual "tab character" (empty space).

Why would I want this? Because I'm generating a config file with a ConfigParser() which also includes some delimiters, and I want that file to be human-readable. I do not consider empty space readable.

EDIT: sorry, the problem was not clear: I want to do this for variables that contain strings. So writing "\\t" is not an option. I must write the value of a variable containing an escaped character to a file in a manner ideologically equivalent to:

v = "\t"
write(v)

without changing the definition of v (though operations on v are OK) It seems impossible to change v into "\\t" after it has been defined as "\t".


回答1:


You need to escape the backslash so it won't be interpreted as a special character:

file_handle.write("\\t")

EDIT: It looks like your best option will be to use python's excellent string.replace() function:

>>> v = "aaa \t bbb"
>>> print v
aaa      bbb
>>> x = v.replace("\t", "\\t")  # <-- replace all '\t' in string with '\\t'
>>> print x
aaa \t bbb

Note: v will be unchanged, since strings are immutable in python

EDIT 2:

Looks like converting to a raw string will take care of escapeing all escaped characters for you:

>>> a = 'aaa\nbbb\n\tccc'
>>> print a
aaa
bbb
        ccc
>>> b = a.encode('string-escape')
>>> print b
aaa\nbbb\n\tccc



回答2:


Escape it.

Instead of writing \t write \\t




回答3:


Lets assume v is 'foo'. You need the escape your single backslash.

v = '\\t %s' % v
print(v)

returns:

\t foo



回答4:


>>> repr('\t')
"'\\t'"

https://docs.python.org/3/library/functions.html#repr




回答5:


I've found a decoder workaround!

from codecs import getencoder as ge, getdecoder as gd
v = "\t"
ge("unicode-escape")(v)[0]
v = gd("utf-8")(byteDelim)[0]
write(v)

using the encoder one can introduce the extra "\" to make a tuple (b'\\t', 1). Then deconstruct the byte-like string in the tuple using another decoder that does not remove the "\", like utf-8.



来源:https://stackoverflow.com/questions/41063524/write-escaped-character-to-file-so-that-the-character-is-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!