How to split a string without spaces in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

How to split a string without spaces in Python #

To split a string without spaces:

  1. Use the list() class to split a string into a list of strings.
  2. Use a list comprehension to split a string into a list of integers.
main.py
my_str = 'abcde' # ✅ split string without spaces into list of characters list_of_strings = list(my_str) print(list_of_strings) # 👉️ ['a', 'b', 'c', 'd', 'e'] # --------------- # ✅ split string without spaces into list of integers my_str_2 = '123456' list_of_ints = [int(x) for x in my_str_2] print(list_of_ints) # 👉️ [1, 2, 3, 4, 5, 6]

The first example uses the list() class to split a string without spaces.

The list class takes an iterable and returns a list object.

When passed a string, the list class splits the string into a list of characters.

If you need to split a string without spaces into a list of integers, use a list comprehension.

main.py
my_str_2 = '123456' list_of_ints = [int(x) for x in my_str_2] print(list_of_ints) # 👉️ [1, 2, 3, 4, 5, 6]

We iterate directly over the string and on each iteration, we convert the digit that is wrapped in a string to an integer.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

An alternative approach is to use the map() function.

main.py
my_str_2 = '123456' list_of_ints = list(map(int, my_str_2)) print(list_of_ints) # 👉️ [1, 2, 3, 4, 5, 6]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We passed the int() class for the function to map and passed it the string for the iterable.

Now the map() function will pass each digit that is wrapped in a string to the int() class.

Note that the map() function returns a map object, so we have to use the list() class to covert the map object to a list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.