Split a string into a list #
In Python, you can split a string into a list of substrings using the split() method. The split() method takes an optional separator as an argument, which is used to split the string into substrings.
If you do not specify the separator, it will default to a space character, like so:
text = "Hello World, this is a test"
words = text.split()
print(words) # ['Hello', 'World,', 'this', 'is', 'a', 'test']
However, you can also specify a different separator to use when splitting the string. For example:
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'orange']
Exercise #
- Change the argument inside the function
split()so that the variablecountriesis a list of country names['USA', 'Canada', 'Mexico', 'Brazil', 'Argentina', 'Peru', 'France', 'Germany', 'Italy', 'Spain']. Make sure to include both the comma and the trailing space to split the text - Do not change the first line of code
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules