Django Split String into List of Characters Example

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


Hi Dev,

This tutorial will provide example of django convert string to list of characters. you will learn how to convert string to list in django. you will learn how to split a string in django by character. This post will give you simple example of django split string into list of characters.

There are several ways to convert strings into a list of characters in django. we will use split() and strip() functions to convert string into list. 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):

    myString = "Site Tuts-Station.com"
  
    # Convert String into List
    newList = list(myString.strip(" "))
      
    print(newList)
    
    return HttpResponse(newList)
Output
['S', 'i', 't', 'e', ' ', 'T', 'u', 't', 's', '-', 'S', 't', 'a', 't', 'i', 'o', 'n', '.', 'c', 'o', 'm']
Example : 2 views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):

    myString = "One,Two,Three,Four,Five"
  
    # Convert String into List
    newList = myString.split(",")
      
    print(newList)

    return HttpResponse(newList)
Output
['One', 'Two', 'Three', 'Four', 'Five']

I Hope It will help you....