Borislav Hadzhiev
Last updated: Jun 25, 2022
Photo from Unsplash
To split a string and count the results:
str.split()
method to split the string into a list of strings.len()
function to get the count of items in the list.my_str = 'a,b,c,d' my_list = my_str.split(',') print(my_list) # 👉️ ['a', 'b', 'c', 'd'] results_count = len(my_list) print(results_count) # 👉️ 4
The len() function returns the length (the number of items) of an object.
The example splits the string on each occurrence of a comma, but you could use any other separator.
# 👇️ split string on spaces my_str = 'a b c d' my_list = my_str.split(' ') print(my_list) # 👉️ ['a', 'b', 'c', 'd'] results_count = len(my_list) print(results_count) # 👉️ 4
The str.split() method splits the original string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
If the separator is not found in the string, a list containing only 1 element is returned.
my_str = 'abcd' my_list = my_str.split(' ') print(my_list) # 👉️ ['abcd'] results_count = len(my_list) print(results_count) # 👉️ 1
If your string starts with or ends with the specific separator, you would get empty string elements in the list.
my_str = '-a-b-c-d-' my_list = my_str.split('-') print(my_list) # 👉️ ['', 'a', 'b', 'c', 'd', ''] results_count = len(my_list) print(results_count) # 👉️ 6
You can use the filter()
function to remove any empty strings from the list.
my_str = '-a-b-c-d-' my_list = list(filter(None, my_str.split('-'))) print(my_list) # 👉️ ['a', 'b', 'c', 'd'] results_count = len(my_list) print(results_count) # 👉️ 6
The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
None
for the function argument, all falsy elements of the iterable are removed.All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Note that the filter()
function returns a filter
object, so we have to use
the list()
class to convert the filter
object to a list.