Python Tutorial: Split String 🎯

beginner
16 min

Python Tutorial: Split String 🎯

Welcome to our comprehensive guide on the Split String concept in Python! This lesson is designed for both beginners and intermediate learners, so let's dive in. 📝

What is a String in Python?

In Python, a string is a sequence of characters. You can think of it as a series of letters, numbers, or symbols enclosed within quotes.

python
my_string = "Hello, World!"

What is String Splitting?

String splitting is the process of dividing a string into multiple parts or substrings based on a specific delimiter. In Python, we use the split() method for this purpose.

The Split() Method 💡

The split() method in Python takes a delimiter as an argument and splits the string based on that delimiter. Here's an example:

python
my_string = "Hello, World!" split_string = my_string.split(',') print(split_string)

Output:

python
['Hello', ' World!']

In the example above, we split the string my_string on the comma (,) delimiter, resulting in two substrings: 'Hello' and 'World!'.

Common Delimiters 📝

Some common delimiters used for string splitting are:

  • Comma (,)
  • Space (' ')
  • Tab ('\t')
  • Semicolon (';')

Splitting on Multiple Delimiters 💡

If you want to split a string on multiple delimiters, you can pass a list of delimiters to the split() method. Here's an example:

python
my_string = "Apple,Banana,Orange" split_string = my_string.split(',') print(split_string)

Output:

python
['Apple', 'Banana', 'Orange']

If you want to retain the multiple delimiters in the resulting list, you can use the split() method without providing any arguments:

python
my_string = "Apple,Banana,Orange" split_string = my_string.split() print(split_string)

Output:

python
['Apple', ',', 'Banana', ',', 'Orange']

Removing Empty Spaces 💡

If you want to remove empty spaces from the resulting list, you can use the strip() method on each element:

python
my_string = " Apple, Banana, Orange " split_string = my_string.split() split_string = [part.strip() for part in split_string] print(split_string)

Output:

python
['Apple', 'Banana', 'Orange']

Quiz 📝

Quick Quiz
Question 1 of 1

What is the output of the following code?