Python str.format() --- passing in list, outputting list

133 views Asked by At

I haven't used str.format() much before and am wondering how to pass in list values and retrieve a list output with these values passed in.

i.e.

listex = range(0, 101, 25)
baseurl = "https://thisisan{0}example.com".format(*listex)

I'd like a list output like ["https://thisisan0example.com", "https://thisisan25example.com", "https://thisisan50example.com", etc etc]

but with my current code above, I'm only getting "https://thisisan0example.com" when I run print baseurl

3

There are 3 answers

2
Bhargav Rao On BEST ANSWER

You cannot get your output as shown using a single format. You can use a list-comp

>>> listex = range(0, 101, 25)
>>> ["https://thisisan{}example.com".format(i) for i in listex]
['https://thisisan0example.com', 'https://thisisan25example.com', 'https://thisisan50example.com', 'https://thisisan75example.com', 'https://thisisan100example.com']

You can use map here (if you are using Py3, wrap a list call),

>>> map("https://thisisan{}example.com".format,listex)
['https://thisisan0example.com', 'https://thisisan25example.com', 'https://thisisan50example.com', 'https://thisisan75example.com', 'https://thisisan100example.com']

This can then be stored in your variable baseurl as

baseurl = map("https://thisisan{}example.com".format,listex)

The speed comparision can be done using timeit

$ python -m timeit 'listex = range(0, 101, 25);["https://thisisan{}example.com".format(i) for i in listex]'
1000000 loops, best of 3: 1.73 usec per loop
$ python -m timeit 'listex = range(0, 101, 25);map("https://thisisan{}example.com".format,listex)'
1000000 loops, best of 3: 1.36 usec per loop

As you can see, the map is faster here (Python2) as there is no involvement of a lambda

0
MrAlexBailey On

You can list comp this:

baseurl = ["https://thisisan{0}example.com".format(x) for x in listex]

This essentially loops through listex and builds baseurl with a unique version of the given string for each element.

0
Rahul Gupta On

Method-1: Using map and lambda:

baseurl = map(lambda x: "https://thisisan{0}example.com".format(x), listex)
['https://thisisan0example.com',
 'https://thisisan25example.com',
 'https://thisisan50example.com',
 'https://thisisan75example.com',
 'https://thisisan100example.com']

Here, map() will apply the lambda function to each element of listex and return a list with the elements changed by the lambda function.

Method-2: Using List comprehension:

baseurl = ["https://thisisan{0}example.com".format(item) for item in listex]
['https://thisisan0example.com',
 'https://thisisan25example.com',
 'https://thisisan50example.com',
 'https://thisisan75example.com',
 'https://thisisan100example.com']

Here, we use list comprehension to achieve the desired result.