python - not enough arguments for format string
黄舟
黄舟 2017-04-18 09:47:56
[Python讨论组]

i = 1
item_add = ''
content = 'test%'
item_add = ('%s' + '.' + content + '<br>') % i
print item_add
执行上面的程序会报错:TypeError: not enough arguments for format string

只要content中含有%的话,python 认为它是转移符,而实际我需要的就是%
我又不能把%进行替换,因为我需要的就是它。。
大家觉得怎么做比较好呢?

源程序是一段django的代码:

def hostcomment_display(self, obj):
    item_add = ''
    i = 1
    for hostcomment_item in h.hostcomment_set.all():
        content = hostcomment_item.comment
        item_add += ('%s' + '.' + content + '\<br\>') % i
        i += 1
    return item_add

如果content中包含%,就报错TypeError: not enough arguments for format string
content = 'software备机--老的备份机-根94%'

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
PHP中文网

打两个%符号:

In [1]: '%stest%%' % i
Out[1]: '1test%'
PHP中文网

我建议你提问题的时候,代码至少也要使用markdown来写。不然你这问题别人看都很难看清楚代码,就更别指望别人来回答你的问题了。至于markdown怎么写,请自行google。

其实你的问题中:

item_add = ('%s test%') % i

如果想要在格式化中显示百分号%, 需要写成%%,因此正确的写法是:

item_add = ('%s test%%') % i
ringa_lee

已经解决了。做了个判断。

        if '%' in content:
            item_add += ('%s' + '.' + content + "%" + '<br>') % i
        else:
            item_add += ('%s' + '.' + content + '<br>') % i
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号