Borislav Hadzhiev
Last updated: Jun 23, 2022
Photo from Unsplash
To split a string and remove whitespace:
str.split()
method to split the string into a list.str.strip()
method to remove the leading and
trailing whitespace.my_str = 'one, two, three, four' my_list = [word.strip() for word in my_str.split(',')] print(my_list) # 👉️ ['one', 'two', 'three', 'four']
We used the str.split()
method to split the string on each occurrence of a
comma.
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 = 'one, two, three, four' l = my_str.split(', ') print(l) # 👉️ ['one', ' two', ' three', ' four']
The next step is to use a list comprehension to iterate over the list of strings.
my_str = 'one, two, three, four' my_list = [word.strip() for word in my_str.split(',')] print(my_list) # 👉️ ['one', 'two', 'three', 'four']
On each iteration, we call the str.strip()
method to remove any leading or
trailing whitespace from the string.
example = ' hello ' print(repr(example.strip())) # 👉️ 'hello'
The str.strip method returns a copy of the string with the leading and trailing whitespace removed.
An alternative approach is to use the map()
function.
To split a string and remove whitespace:
str.split()
method on the string to get a list of strings.str.strip
method and the list to the map()
function.map
function will call the str.strip
method on each string in the
list.my_str = 'one, two, three, four' my_list = list(map(str.strip, my_str.split(','))) print(my_list) # 👉️ ['one', 'two', 'three', 'four']
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
str.strip
method as the function, so the map
function is going to call the str.strip()
method on each item in the list.The map
function returns a map object (not a list). If you need to convert the
value to a list, pass it to the list()
class.
Which approach you pick is a matter of personal preference. I'd go with the list comprehension as it is a bit more readable and explicit.