Python string from list comprehension

Python string from list comprehension

You need to join your string like this:

markers = [(97,64),(45,84)]
result = .join(&markers=%s % ,.join(map(str, x)) for x in markers)
return result

UPDATE

I didnt initially have the ,.join(map(str, x)) section in there to turn each tuple into strings. This handles varying length tuples, but if you will always have exactly 2 numbers, you might see gattos comment below.

The explanation of whats going on is that we make a list with one item for each tuple from markers, turning the tuples into comma separated strings which we format into the &markers= string. This list of strings is then joined together separated by an empty string.

While the first answer is doing whats expected, Id make it a bit more pythonic by getting rid of map and nested expressions:

def join(seq, sep=,):
    return sep.join(str(i) for i in seq)

result = .join(&markers=%s % join(m) for m in markers)

(if thats for urls like it seems, you can also take a look at urllib.urlencode)

Python string from list comprehension

In Python 3.6 you could write:

markers = [(97,64),(45,84)]
result = print(.join(f&markers={pair} for pair in markers))
return result

Leave a Reply

Your email address will not be published. Required fields are marked *