Python ConfigParser - 引号之间的值

13 python configparser

使用ConfigParser模块时,我想使用包含cfg文件中设置的多个单词的值.在这种情况下,使用像(example.cfg)这样的引号来包围字符串似乎微不足道:

[GENERAL]
onekey = "value in some words"
Run Code Online (Sandbox Code Playgroud)

我的问题是,在这种情况下,python在使用这样的值时也会将引号附加到字符串:

config = ConfigParser()
config.read(["example.cfg"])
print config.get('GENERAL', 'onekey')
Run Code Online (Sandbox Code Playgroud)

我确信有一个内置功能来管理只打印'value in some words'而不是'"value in some words"'.这怎么可能?谢谢.

Mar*_*off 12

我在configparser手册中没有看到任何内容,但您可以使用.strip字符串方法来删除前导和尾随双引号.

>>> s = '"hello world"'
>>> s
'"hello world"'
>>> s.strip('"')
'hello world'
>>> s2 = "foo"
>>> s2.strip('"')
'foo'
Run Code Online (Sandbox Code Playgroud)

如您所见,.strip如果字符串不以指定的字符串开头和结尾,则不会修改该字符串.

  • 注意最后一句应该更新。`strip()` 确实会修改字符串,如果它以指定的字符串开头或结尾。例如`'"bar'.strip("'")` 返回`'bar` 而不是`bar`。 (2认同)

小智 6

import ConfigParser

class MyConfigParser(ConfigParser.RawConfigParser):
    def get(self, section, option):
        val = ConfigParser.RawConfigParser.get(self, section, option)
        return val.strip('"')

if __name__ == "__main__":
    #config = ConfigParser.RawConfigParser()
    config = MyConfigParser()

    config.read(["example.cfg"])
    print config.get('GENERAL', 'onekey') 
Run Code Online (Sandbox Code Playgroud)


小智 5

抱歉,解决方案也很简单 - 我可以简单地留下引号,看起来 python 只是在等号的右侧。


est*_*ani 5

这个问题已经很老了,但在 2.6 中至少你不需要使用引号,因为空格被保留。

from ConfigParser import RawConfigParser
from StringIO import StringIO

s = RawConfigParser()
s.readfp(StringIO('[t]\na= 1 2 3'))
s.get('t','a')
> '1 2 3'
Run Code Online (Sandbox Code Playgroud)

但这不适用于前导空格或尾随空格!如果您想保留这些内容,则需要将它们括在引号中并按照建议进行。避免使用eval关键字,因为您将面临巨大的安全漏洞。