【问题标题】:Is there a way to clean up this code to make it more efficient and not look so messy?有没有办法清理这段代码,让它更有效率,而且看起来不那么凌乱?
【发布时间】:2018-03-23 17:59:11
【问题描述】:

我有 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

提前谢谢你。

【问题讨论】:

  • 嘿@arekenny3,你用的是python3还是python 2?
  • 我认为codereview 更适合回答这样的问题
  • 这个问题和twiliomms标签有什么关系?

标签: python performance twilio mms


【解决方案1】:

你可以使用str.format

例如:

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

【讨论】:

  • 另外,如果@arekenny3 使用python 3.6 或更高版本,他可以使用fstrings。对于范围 (1,3) 中的 n:media_url = f"exampleaddress.com/rowdycode/wow{n}.jpg"
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    你可以用喜欢

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

    【讨论】:

      【解决方案4】:

      使用列表推导式存储结果(即地址)。

      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) 
      

      【讨论】:

        猜你喜欢
        • 2020-08-22
        • 2019-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多