有没有办法清理这段代码,让它更有效率,而不是看起来那么乱?

Is there a way to clean up this code to make it more efficient and not look so messy?

我要发送 2 张 .jpg 图片。它们的名称如下:'wow1'、'wow2'。下面的代码在我发送时有效,但看起来不太漂亮。我该如何清理它?

for n in range (1,3):
    address = 'http://exampleaddress.com/rowdycode/wow'
    extension = '.jpg'
    picture =str(n)
    p = str(address+picture+extension)
    media_url = p

如果我给它一个打印函数,它打印如下:

http://exampleaddress.com/rowdycode/wow1.jpg
http://exampleaddress.com/rowdycode/wow2.jpg

提前致谢。

您可以使用str.format

例如:

for n in range (1,3):
    media_url = 'http://exampleaddress.com/rowdycode/wow{0}.jpg'.format(n)

你可以使用 like

for n in range (1,3):
    address = 'http://exampleaddress.com/rowdycode/wow%d.jpg'%(n)

从 python 3.6 开始,您还可以使用 Literal String Interpolation(f-strings)

address = [f'http://exampleaddress.com/rowdycode/wow{n}.jpg' for n in range(1,3)]

使用列表理解存储结果(即 addresses)。

my_list = ['http://exampleaddress.com/rowdycode/wow{}.jpg'.format(n) for n in range(1,3)]

或者我们可以使用f-strings(在Python 3.6中引入)

my_list = [f'http://exampleaddress.com/rowdycode/wow{n}.jpg' for n in range(1,3)]


# print(my_list) for testing purposes

在 for 循环中做同样的事情:

for n in range(1,3):
    address = f'http://exampleaddress.com/rowdycode/wow{n}.jpg'
    # print (address)