首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python ConfigParser -引号之间的值

Python ConfigParser -引号之间的值
EN

Stack Overflow用户
提问于 2009-08-21 11:12:51
回答 6查看 17.3K关注 0票数 17

当使用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"'。这怎么可能呢?谢谢。

EN

回答 6

Stack Overflow用户

发布于 2009-08-21 11:17:38

我在the configparser manual中看不到任何东西,但是您可以只使用字符串的.strip方法去掉前导和尾部的双引号。

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

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

票数 14
EN

Stack Overflow用户

发布于 2010-02-01 20:23:03

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') 
票数 8
EN

Stack Overflow用户

发布于 2009-08-21 11:21:07

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1311367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档