Python ConfigParser - 引号中的值

23 投票
8 回答
21518 浏览
提问于 2025-04-15 13:46

在使用 ConfigParser 模块时,我想在配置文件中使用包含多个单词的值。在这种情况下,我觉得只需用引号把字符串包起来就可以了,比如在 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"'。这怎么做到呢?谢谢。

8 个回答

6

抱歉,解决办法其实很简单——我只需要保留引号就可以了,看来Python只是看等号右边的内容。

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

16

我在configparser手册里没看到相关内容,不过你可以直接用字符串的.strip方法来去掉开头和结尾的双引号。

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

正如你所看到的,如果字符串的开头和结尾不是指定的内容,.strip就不会改变这个字符串。

撰写回答