Skip to content

Python split string by character | Example code

  • by

Using List Comprehension or Typecasting to list will split string by character in Python. Both methods will convert a string into a char of a list.

Simply take the string and pass it to the list().

Note: You can’t use the split method for it, because this method needed a separator.

Python split string by character example

Simple example code.

Using List Comprehension

s = "Hello"
res = [char for char in s]

print(res)

Typecasting to list 

Using list function to direct typecasting of string into a list.

s = "Hello"
res = list(s)

print(res)

Output:

Python split string by character

Using for loop

This method will print each char, not as a list.

s = "Hello"
for c in s:
    print(c)

Output:

H
e
l
l
o

You can use any character as the delimiter to split the string. For example, to split a string by a hyphen, you can use the following code:

my_string = "red-green-blue"
my_list = my_string.split("-")
print(my_list)  # ['red', 'green', 'blue']

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