Python 从配置文件中删除一个字符串

Python strip a string from config file

我有一个配置文件,其中包含一个以制表符分隔的字符串。我想检索该字符串,然后将其转换为一个漂亮的列表。但是,当我直接在 iPython.

上执行时,我看到了一些我看不到的有趣的东西
[myvars]
myString = "a\tb\tc\td"
.....
.....<many more variables>

我的 Python 代码是这样的:

param_dict = dict(config.items(myvars))
str1 = param_dict["myString"]
print str1
print str1.split()

然后打印出来:

"a\tb\tc\td"
['"a\tb\tc\td"']

但是,当我在我的 python 控制台上做同样的事情时,我得到了我期望的结果:

Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "a\tb\tc\td".split()
['a', 'b', 'c', 'd']
>>> k = "a\tb\tc\td"
>>> k.split()
['a', 'b', 'c', 'd']

这是怎么回事?有人可以帮我吗?我无法更改配置文件变量的格式。而且,我想取出变量并剥离到一个漂亮的列表中。

谢谢。

此处正在读取反斜杠,打印普通字符串时看不到它,但打印 repr 时会看到。

In [11]: myString = "a\tb\tc\td"

In [12]: print(myString)
a\tb\tc\td

In [13]: print(repr(myString))
'a\tb\tc\td'

您可以使用解码将 \t 转换为 \t:

In [14]: myString.decode('string_escape')
Out[14]: 'a\tb\tc\td'

一旦它们成为标签,您就可以拆分它们:

In [15]: myString.split()
Out[15]: ['a\tb\tc\td']

In [16]: myString.decode('string_escape').split()
Out[16]: ['a', 'b', 'c', 'd']

发生这种情况是因为在你的 "script" 中你没有 "a\tb\tc\td" 你真的有 "a\tb\tc\td" 但是如果你打印 "a\tb\tc\td" 它会输出 "a\tb\tc\td"

print myString
Output: 'a\tb\tc\td'
print repr(myString)
Output: 'a\tb\tc\td'

您可以使用函数 decode 将字符串从 'a\tb\tc\td' 转换为 'a\tb\tc\td' 然后拆分或任何您需要的

import re
myString = "a\tb\tc\td"

# I prefer to use regular expressions to deal with strings:
myString = re.sub(r'\W','', myString.decode('string_escape'))
print myString
Output: 'abcd'

# Or you can use split also
myString = myString.decode('string_escape').split()
print myString
Output: ['a', 'b', 'c', 'd']

据我所知,您错误地认为您的字符串在您的文件中是制表符分隔的,它由两个字符“\”和代表制表符的 "t" 分隔。这由带有转义反斜杠的表示形式显示:"a\tb" 而不是 "a\tb"

由于没有空格字符,sort 不知道如何拆分字符串。

你可以在split中指定不同的分隔符,这里是两个字符\t:

str1.split("\t")