How to Convert List into String in Django?

Published On: 30/07/2022 | Category: Django Python


Hi Dev,

Are you looking for example of how to convert list into string in django. we will help you to give example of how to turn list into string in django. I’m going to show you about django convert list to string. This article goes in detailed on django convert list into string value.

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

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

let's see below 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
12345
Example : 3 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 = '';
      
    for str in myList:
        newString += ' ' + str;
      
    print(newString)

    return HttpResponse(newString)
Output
one two three four five

I Hope It will help you....