split(): Divide Strings into Substrings by Delimiter

split() returns a list after breaking a string using delimiter and max value
my_str.split(delimiter,max_value) 
delimiter : (default is space), required, to be used to break the string
max_value : optional , the number of elements in output plus one. Default value is -1 so it includes all occurrence.
my_list="'Alex','Ronald','John'"
my_list=my_list.split(',')
print(my_list)

my_list="'Alex','Ronald','John'"
my_list=my_list.split(',',1)
print(my_list)
output
["'Alex'", "'Ronald'", "'John'"]
["'Alex'", "'Ronald','John'"]
By using rsplit() in place of split(), the output will change like this. ( difference between rsplit() and split() )
["'Alex'", "'Ronald'", "'John'"]
["'Alex','Ronald'", "'John'"]

Example 1: Basic split() Usage

text = "apple orange banana"
fruits = text.split()
print(fruits)
Output:
['apple', 'orange', 'banana']

Example 2: Custom Delimiter

Using a comma as a delimiter to split CSV-like data.
data = "name,age,location"
values = data.split(',')
print(values)
Output:
['name', 'age', 'location']

Example 3: Using maxsplit

Control the number of splits using maxsplit.
text = "apple-orange-banana-pear"
result = text.split('-', 2)
print(result)
Output:
['apple', 'orange', 'banana-pear']

Example 4: Split with rsplit() for Right Splits

rsplit() splits from the right side of the string.
text = "apple-orange-banana-pear"
result = text.rsplit('-', 2)
print(result)
Output:
['apple-orange', 'banana', 'pear']

Example 5: Splitting Each Word from User Input

Useful for processing phrases into words.
phrase = input("Enter a phrase: ")
words = phrase.split()
print("Words:", words)

Use Cases for split()

  • Data Parsing: Split data read from files or user input.
  • Data Processing: Transform strings to lists for iteration or filtering.
  • Working with CSV Data: Manually parse CSV rows if a CSV parser isn't used.

All String methods


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer