Split & Join
Lists and strings are different. In some cases, a list will be preferable to a string, and in other cases, it will be the opposite.
It is important to know that you can easily transform a list into a string or a string into a list. You can do this using the split
and join
methods described below.
Split
To convert a string into a list, we will in fact split the string using the split
method.
my_text = "Hello World"
my_text = my_text.split(" ")
print(my_text) # Will print ['Hello', 'World']
The parameter we give to the split method will impact how the string will be split. Here we ask to split it when there is a space.
Join
To convert a list into a string, we will join the different elements of the list using the join
method.
my_list = ["Hello", "World"]
my_list = " ".join(my_list)
print(my_list) # Will print 'Hello World'
The parameter given to the join method is the list and we apply this method on a string (here a single space). It will insert that string between each element of the list.
Exercise 13
Save your code in your Python
folder and call it exercise13
.
Write a program that will:
- Create a variable
text
and assign the following to it: βHello,everybody,how,are,you,doing?β - Split
text
on the,
delimiter and assign it to a variable calledresult
- Print
result
- Join the text back in the variable
result
, adding a space delimiter this time and assign it to the variableresult2
- Print
result2
Help
- To split a text on a
#
character, you write:my_text = my_text.split("#")
- To join a list on a
,
character, you write:my_list = ",".join(my_list)
- You should get the following result: