【问题标题】:Python placeholders in strings containing the % symbol包含 % 符号的字符串中的 Python 占位符
【发布时间】:2013-05-24 08:38:38
【问题描述】:

我希望能够在已经包含% 符号的字符串中使用占位符。例如,我希望能够通过我的 URL 已经包含 % 符号来迭代打开多个 URL,例如 url:

http://www.example.com/BLABLA%123BLABLApage=1

为此,我想用占位符 (%d) 替换数字 1,但代码似乎被占位符之前的 % 的存在弄糊涂了。

【问题讨论】:

    标签: python placeholder


    【解决方案1】:

    你可以通过加倍来逃避%

    >>> 'http://www.example.com/BLABLA%%123BLABLApage=%d' % (1,)
    'http://www.example.com/BLABLA%123BLABLApage=1'
    

    或者,改用str.format() 格式:

    >>> 'http://www.example.com/BLABLA%123BLABLApage={:d}'.format(1)
    'http://www.example.com/BLABLA%123BLABLApage=1'
    

    【讨论】:

    • 可能想添加format 的使用,例如"http://www.example.com/BLABLA%123BLABLApage={page}".format(page=1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多