Django Convert List into String with Commas Example

Published On: 13/08/2022 | Category: Django


Hi Dev,

This article goes in detailed on django convert list into string with commas. you will learn django convert list to string comma separated. I would like to share with you django convert list to comma separated string with quotes. This post will give you simple example of how to convert list to string with comma in django.

There are several ways to convert the list into a string with commas separated in django. we will use join() and for loop to convert list to string comma separated. so let's see the below examples.

You can use these examples with django3 (Django 3) version.

let's see below a simple example with output:

Example : 1 views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):

    myList = ['one', 'two', 'three', 'four', 'five']
  
    # Convert List into String
    newString = ','.join(myList)
    print(newString)
    
    return HttpResponse(newString)
Output
one,two,three,four,five
Example : 2 views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    
    myList = [1, 2, 3, 4, 5]
  
    # Convert List into String
    newString = ','.join(str(x) for x in myList)
    print(newString)
    
    return HttpResponse(newString)
Output
1,2,3,4,5

I Hope It will help you....