Editor

Python Program to Split a String into a List

Beginner · Strings

Splitting a string means cutting it into pieces at a separator, such as a space or a comma, and getting the pieces back as a list. It is how programs read the words of a sentence or the values on a line of a CSV file.

Program

split_string.py
sentence = "Python is easy to learn" # or: sentence = input("Enter a sentence: ")
csv_line = "apple,banana,cherry,mango"
words = sentence.split() # split on spaces
fruits = csv_line.split(",") # split on commas
print("Words:", words)
print("Fruits:", fruits)
print("Number of fruits:", len(fruits))
print("Second fruit:", fruits[1])
print("Two commas in a row:", "a,,b".split(","))
Output
Words: ['Python', 'is', 'easy', 'to', 'learn']
Fruits: ['apple', 'banana', 'cherry', 'mango']
Number of fruits: 4
Second fruit: banana
Two commas in a row: ['a', '', 'b']

How it works

  1. split() with no argument cuts the string at every run of spaces, tabs or new lines.
  2. split(",") cuts at every comma instead, and the separator itself is not kept in the pieces.
  3. Both return an ordinary list, so len(), indexing like fruits[1] and loops all work on the result.
  4. With a separator given, two separators in a row leave an empty string between them, as the last line shows.

Other ways to write it

Characters, a limited split and cleaning up

Characters, a limited split and cleaning up
word = "Python"
print("Characters:", list(word))
line = "name=Riya=Sharma"
print("Split once:", line.split("=", 1))
messy = "red , green, blue"
colours = [part.strip() for part in messy.split(",")]
print("Cleaned:", colours)
Output
Characters: ['P', 'y', 't', 'h', 'o', 'n']
Split once: ['name', 'Riya=Sharma']
Cleaned: ['red', 'green', 'blue']

list() splits a string into single characters, the second argument of split() limits the number of cuts, and strip() removes the spaces left around each piece.

Without split()

Without split()
text = "apple,banana,cherry,mango"
items = []
current = ""
for ch in text:
if ch == ",":
items.append(current) # a comma ends the current item
current = ""
else:
current += ch
items.append(current) # the last item has no comma after it
print("List:", items)
Output
List: ['apple', 'banana', 'cherry', 'mango']

The loop collects characters into current and saves it whenever a comma arrives. The last item has to be saved after the loop, because no comma follows it.

Try it yourself

Split the date "18-10-2026" on "-" and print the day, the month and the year on separate lines.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises