ValueError: unsupported format character 'p' (0x70) at index 7

ValueError: unsupported format character 'p' (0x70) at index 7

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

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

语法需要%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 - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point with fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)