将转义的字符写入文件,以便字符可见 [英] write escaped character to file so that the character is visible
问题描述
我该怎么做?一直把我疯狂了一个多小时,我尝试的一切都会产生一个实际的制表符(空格)。
为什么要这样?因为我正在使用ConfigParser()生成一个配置文件,它也包含一些分隔符,而且我希望这个文件是可读的。我不认为空间可读。
编辑:对不起,问题不清楚:我想为包含字符串的变量做这个。所以写\\不是一个选项。我必须以意想不到的方式将含有转义字符的变量的值写入到文件中:
v =\\ \\ t
写(v)
而不更改 v
(虽然在 v
上的操作可以)
似乎不可能更改 v
在被定义为\t之后变为\\\t。
以避免反斜杠,因此它不会被解释为特殊字符:
file_handle.write(\\t )
编辑:看起来你最好的选择是使用python的优秀的 string.replace()
function:
>> > v =aaa \t bbb
>>>打印v
aaa bbb
>>> x = v.replace(\t,\\)#< - 用'\\\''替换字符串中的所有'\'
>> >打印x
aaa \t bbb
注意: v
将保持不变,因为字符串在python中是不可变的
编辑2:
看起来转换为原始字符串将会为您避免转义所有转义的字符:
> >> a ='aaa\\\
bbb\\\
\tccc'
>>>>打印
aaa
bbb
ccc
>>> b = a.encode('string-escape')
>>>打印b
aaa\\\
bbb\\\
\tccc
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".
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
这篇关于将转义的字符写入文件,以便字符可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!