Python split() Method Explained

In Python, the split() method is used to divide a string into a list based on a specified delimiter. By default, the split() method uses a space as the delimiter. For example:

s = "hello world"
words = s.split()
print(words)  # ['hello', 'world']

To split based on a different delimiter, you can pass the delimiter as a parameter to the split() method. For example, to split by comma:

s = "apple,orange,banana"
fruits = s.split(",")
print(fruits)  # ['apple', 'orange', 'banana']

In addition, the split() method can also specify the number of splits, as shown below:

s = "hello world how are you"
words = s.split(" ", 2)
print(words)  # ['hello', 'world', 'how are you']

In the example above, the number of separations is specified as 2, meaning it will be divided a maximum of two times.

bannerAds