Tutorials
python

String Split in Python

Learn how you can perform various operations on string using built-in Python functions like split, join and regular expressions, and also convert them to other data types like lists.

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:

print(string.lower())
this is a nice string

On the contrary, you may want the string to be uppercase.

print(string.upper())
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 .split() and .rsplit().

string.split(sep=" ", maxsplit=2)
['This', 'string', 'will be split']
string.rsplit(sep=" ", maxsplit=2)
['This string will', 'be', 'split']

Exercise

TRY IT YOURSELF: Access the exercise in our Regular Expressions in Python course here.

  • Split the string file into many substrings at line boundaries.
  • Print out the resulting variable file_split.
  • 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)

Video

To learn more about string operations, please see this video from our course Regular Expressions in Python.

This content is taken from DataCamp’s Regular Expressions in Python course by Maria Eugenia Inzaugarat.