I am trying to get this string as a result:
"&markers=97,64&markers=45,84"
From the Python code below:
markers = [[97,64],[45,84]]
result = ["&markers=%s" %x for x in markers]
return result
How do I do this as the below does not give me the actual string?
Gino Mempin
20.7k24 gold badges84 silver badges111 bronze badges
asked Apr 30, 2013 at 14:21
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 didn't 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 gatto's comment below.
The explanation of what's 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.
perror
6,81516 gold badges59 silver badges81 bronze badges
answered Apr 30, 2013 at 14:23
underrununderrun
6,5532 gold badges38 silver badges53 bronze badges
3
In Python 3.6 you could write:
markers = [[97,64],[45,84]]
result = ''.join[f'&markers={pair}' for pair in markers]
return result
Gino Mempin
20.7k24 gold badges84 silver badges111 bronze badges
answered Oct 16, 2018 at 15:46
PlutoPluto
6969 silver badges8 bronze badges
0
While the first answer is
doing what's expected, I'd 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 that's for urls like it seems, you can also take a look at urllib.urlencode
]
answered Apr 30, 2013 at 14:41
berealbereal
30.2k6 gold badges53 silver badges93 bronze badges
2
Here's another approach that hopefully makes the intent the most clear by specifying the location of each of your values explicitly:
markers = [[97,64],[45,84]]
print ''.join['&markers=%s,%s' % pair for pair in markers]
answered Apr 30, 2013 at 14:42
hexparrothexparrot
3,3211 gold badge22 silver badges32 bronze badges
Try creating an empty string adding to it then removing the last comma
result = ''
for i in a:
result+='&markers'
for j in i:
result += str[j] + ','
result = result[:len[result]-1]
return result
answered Apr 30, 2013 at 14:44