6

i have array like below

arr = [1,2,3]

how can i convert it to '1,2,3' using python

i have a usecase where i want to add a filter parameter to url like below

url = some_url?id__in=1,2,3

i was initially thinking to pass it like so

url = some_url?id__in={arr} 

but this is incorrect. i am new to python and i have browsed how to do this.

" ".join(str(x) for x in arr)

but this will give output '1 2 3'

how can i fix this. could someone help me with this. thanks.

Balaji
  • 795
  • 1
  • 2
  • 10
stackuser
  • 253
  • 1
  • 2
  • 14
  • 2
    Use ``",".join(str(x) for x in arr)`` instead of ``" ".join(str(x) for x in arr)``. – MisterMiyagi Oct 05 '21 at 09:16
  • You are just missing comma (,) in your code. Use `",".join(str(x) for x in a)` – Pran Sukh Oct 05 '21 at 09:21
  • What module are you using for performing request? Is it [`requests`](https://docs.python-requests.org/en/latest/)? Common way to send list is `?id__in=1&id__in=2&id__in=3"` not `id__in=1,2,3"` – Olvin Roght Oct 05 '21 at 09:25

3 Answers3

9

This gives you the 1,2,3 that you asked for.

",".join(str(x) for x in arr)

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
3

Try the below

arr = [1,2,3]
string = ','.join(str(x) for x in arr)
print(string)

output

1,2,3
balderman
  • 22,927
  • 7
  • 34
  • 52
1

You could join on the , character instead of a space:

",".join(str(x) for x in arr)
Mureinik
  • 297,002
  • 52
  • 306
  • 350