Skip to content

How to split a word in Python | Example code

  • by

Do typecast to convert a string into the list of char. For it use the list() function to split a word into a list of letters in Python.

The syntax for the split() method is as follows:

string.split([separator[, maxsplit]])

How to split a word in Python example

A simple example code splitting a word into a list of chars creates a list.

word = "word"

res = list(word)

print(res)

Output:

How to split a word in Python

Here are some additional methods you can use:

1. Using slicing: You can split a word into substrings using slicing. Here’s an example:

word = "Hello"
split_word = [word[i:i+1] for i in range(0, len(word))]
print(split_word)
# Output: ['H', 'e', 'l', 'l', 'o']

2. Using regular expressions: You can also use regular expressions to split a word into substrings based on a pattern.

import re

word = "Hello,world"
split_word = re.split(",|\s", word)
print(split_word)
# Output: ['Hello', 'world']

3. Using the list() constructor: You can convert a string to a list of characters using the list() constructor, and then join the list of characters back into a string using the join() method.

word = "Hello"
split_word = list(word)
print(split_word)
# Output: ['H', 'e', 'l', 'l', 'o']

Is there a function in Python to split a word into a list?

The easiest way is probably just to use list(), but there is at least one other option as well:

s = "Word to Split"

wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension

print(wordlist)

Output: [‘W’, ‘o’, ‘r’, ‘d’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘S’, ‘p’, ‘l’, ‘i’, ‘t’]

Do comment if you have any doubts or suggestions on this Python split topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading