-1

I have 2 .jpg pictures that I am sending. They both are called as follows: 'wow1', 'wow2'. The code below works when I send it, but it doesn't look very pretty. How can I clean this up?

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

If I give it a print function, it prints as follows:

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

Thank you in advance.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
arekenny3
  • 43
  • 4

4 Answers4

2

You can use str.format

Ex:

for n in range (1,3):
    media_url = 'http://exampleaddress.com/rowdycode/wow{0}.jpg'.format(n)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Alternatively, if @arekenny3 is using python 3.6 or greater he can use fstrings. for n in range (1,3): media_url = f"http://exampleaddress.com/rowdycode/wow{n}.jpg" – Peter Dolan Mar 23 '18 at 18:01
1

you can use like

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

From python 3.6, you can also use Literal String Interpolation(f-strings)

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

Store the results (i.e. addresses) it using a list comprehension.

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

or we can use f-strings (Introduced in 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

Doing the same within a for loop:

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