String Split in Python
Python has many built-in methods that allow us to handle strings. Let's check out some of them.
Suppose you have a string like the one in the example code:
string = 'tHis Is a Nice StriNg'
Sometimes the analysis require the string to be entirely lowercase. You could use the
.lower() method to convert all the alphabetical characters to lowercase as shown below:
this is a nice string
On the contrary, you may want the string to be uppercase.
THIS IS A NICE STRING
There are methods that can convert strings into other data types like
lists by breaking a string into pieces.
string = 'this string will be split'
You want to split this string into a list of substrings. Python provides you with two methods
string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']
TRY IT YOURSELF: Access the exercise in our Regular Expressions in Python course here.
- Split the string
fileinto many substrings at line boundaries.
- Print out the resulting variable
- Complete the for-loop to split the strings into many substrings using commas as a separator element.
# Split string at line boundaries file_split = ____ # Print file_split print(____) # Complete for-loop to split by commas for ____ in ____: substring_split = substring.____ print(substring_split)
To learn more about string operations, please see this video from our course Regular Expressions in Python.