Python ConfigParser-引号之间的值

2024-05-12 21:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用ConfigParser模块时,我希望使用包含cfg文件中设置的多个单词的值。在这种情况下,对我来说用引号将字符串括起来似乎很简单,比如(example.cfg):

[GENERAL]
onekey = "value in some words"

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

config = ConfigParser()
config.read(["example.cfg"])
print config.get('GENERAL', 'onekey')

我确信有一个内置的功能可以只打印'value in some words',而不是'"value in some words"'。怎么可能?谢谢。


Tags: 模块文件字符串inconfigvalueexample情况
3条回答

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

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') 

我在the configparser manual中没有看到任何内容,但是您可以使用字符串的.strip方法去掉前导双引号和尾随双引号。

>>> s = '"hello world"'
>>> s
'"hello world"'
>>> s.strip('"')
'hello world'
>>> s2 = "foo"
>>> s2.strip('"')
'foo'

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

相关问题 更多 >