Python String split | List of words and characters examples

This tutorial explains String split into multiple strings and characters

To convert a string to a list of characters, the following approaches are used

  • List constructor
  • for in-loop and list comprehension syntax
  • String iterable unpacking operator To convert a string to a list of words, the String split() function is used with a delimiter.

Python Convert String to List of characters

For example, If the input contains “string”, It is converted to ['s', 't', 'r', 'i', 'n', 'g']

Multiple ways we can do this.

  • use List constructor.

list(string) takes string input parameters and generates a list from a given iterable in a string. It returns a List of characters

ar=list("string")
print(ar)

Output:

['s', 't', 'r', 'i', 'n', 'g']
  • use for loop with append character

This is a legacy way of iterating a string using for in loop Each iteration returns characters and appends to an empty list. Finally, print the list

output = []
for char in "character":
output.append(char)
print(output)

Output:

['c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r']

The same above syntax can be replaced with a simplified syntax list comprehension

out = [char for char in "character"]
print(out)
  • using iterable unpacking operator

Python 3.5 introduced the * symbol called the iterable unpacking operator, which unpacks the iterable elements. String object unpacks into characters and used those in square brackets []. Here is an example

chars = "unpackingsymbol"
print([*chars])

Output:

['u', 'n', 'p', 'a', 'c', 'k', 'i', 'n', 'g', 's', 'y', 'm', 'b', 'o', 'l']

How to Convert String into List of words

`String split() function split the string into multiple strings based on a delimiter. The default is space.

Syntax

str.split([sep[, maxsplit]])

Sep is a separator or delimiter, and default is a space maxsplit is a limit on the number of splits Returns the list of words from a string delimited by space.

Here is an example

sentence = "Hello Welcome to my python tutorial and examples"
ar=sentence.split()
print(ar)
print(type(ar)) #<class 'list'>

Output:

['Hello', 'Welcome', 'to', 'my', 'python', 'tutorial', 'and', 'examples']
<class 'list'>