Python String split() Method

The Python split() method is a string method that splits a string into a list of substrings, using a specified separator as the delimiter. It has the following syntax:

string.split(separator, maxsplit)

where separator is an optional parameter that specifies the string to split on (default is any whitespace), maxsplit is an optional parameter that specifies how many splits to do from the left (default is -1, which means all possible splits).

The split() method returns a list of substrings after splitting the string.

Here are some examples of using the Python split() method:

# Example 1: Split a string by space
mystr = 'welcome to the jungle'
result = mystr.split()
print(result)

# Output: ['welcome', 'to', 'the', 'jungle']

# Example 2: Split a string by comma and space
mystr = 'hello, my name is Peter, I am 26 years old'
result = mystr.split(', ')
print(result)

# Output: ['hello', 'my name is Peter', 'I am 26 years old']

# Example 3: Split a string by hash character with maxsplit=2
mystr = 'apple#banana#cherry#orange'
result = mystr.split('#', 2)
print(result)

# Output: ['apple', 'banana', 'cherry#orange']

If you have any questions about this code, you can drop a line in comment.

 

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions