【问题标题】:ValueError: unsupported format character 'p' (0x70) at index 7ValueError:索引 7 处不支持的格式字符“p”(0x70)
【发布时间】:2018-11-11 13:09:27
【问题描述】:

我正在尝试使用循环格式化字符串文件名,这是我的代码

for i in range(1, 16):
    bgImageFile = ("bg_%01.png" %i)

【问题讨论】:

    标签: python string python-3.x string-formatting


    【解决方案1】:

    语法需要%d(或%s),而不仅仅是%:

    for i in range(1, 4):
        bgImageFile = 'bg_%s01.png'%i
        print(bgImageFile)
    
    bg_101.png
    bg_201.png
    bg_301.png
    

    在 Python 3.6+ 中,您可以使用 f-strings (PEP498):

    for i in range(1, 4):
        bgImageFile = f'bg_{i}01.png'
    

    你应该知道的一些说明符 (source):

    %s - 字符串(或任何具有字符串表示的对象,例如 数字)

    %d - 整数

    %f - 浮点数

    %.<number of digits>f - 固定位数的浮点数 点的右边。

    %x/%X - 十六进制表示的整数 (小写/大写)

    【讨论】:

    • 谢谢,但我在 OpenCV 上出现另一个错误 imshow 它说 cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\highgui\src\window .cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
    • @Redemption,好的,如果没有连接到这个问题,请ask a new one。
    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 2020-08-25
    • 2017-12-07
    • 2023-03-29
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多