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. 📝
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.
my_string = "Hello, World!"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 in Python takes a delimiter as an argument and splits the string based on that delimiter. Here's an example:
my_string = "Hello, World!"
split_string = my_string.split(',')
print(split_string)Output:
['Hello', ' World!']In the example above, we split the string my_string on the comma (,) delimiter, resulting in two substrings: 'Hello' and 'World!'.
Some common delimiters used for string splitting are:
,)' ')'\t')';')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:
my_string = "Apple,Banana,Orange"
split_string = my_string.split(',')
print(split_string)Output:
['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:
my_string = "Apple,Banana,Orange"
split_string = my_string.split()
print(split_string)Output:
['Apple', ',', 'Banana', ',', 'Orange']If you want to remove empty spaces from the resulting list, you can use the strip() method on each element:
my_string = " Apple, Banana, Orange "
split_string = my_string.split()
split_string = [part.strip() for part in split_string]
print(split_string)Output:
['Apple', 'Banana', 'Orange']What is the output of the following code?