Monday, January 6, 2025
HomeProgrammingPython String Split

Python String Split

 

The split() method in Python is used to split a string into a list of substrings based on a specified delimiter (separator). If no separator is provided, it splits on whitespace by default.

Syntax
python
string.split(separator, maxsplit)

– separator (optional): The delimiter on which the string will be split. Default is any whitespace.
– maxsplit (optional): Specifies the maximum number of splits. The default is -1, which means no limit.

See also  How to Run a PowerShell Script on Windows

Examples

  • Split on Whitespace (Default)
    python
    text = “Python is fun”
    words = text.split()
    print(words) # Output: [‘Python’, ‘is’, ‘fun’]
  • Split Using a Specific Separator
    python
    text = “apple,banana,cherry”
    fruits = text.split(“,”)
    print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry’]
  • Using maxsplit
    python
    text = “apple,banana,cherry,grape”
    fruits = text.split(“,”, maxsplit=2)
    print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry,grape’]
  • Split Using Multiple Whitespace
    python
    text = ” Python is fun ”
    words = text.split()
    print(words) # Output: [‘Python’, ‘is’, ‘fun’]
  • Split Using Special Characters
    python
    text = “hello#world#python”
    parts = text.split(“#”)
    print(parts) # Output: [‘hello’, ‘world’, ‘python’]
See also  Simplest Way to Print a Java Array

Points to Remember
1. If no separator is specified, split() treats consecutive whitespace as a single separator.
2. If the string does not contain the separator, the entire string is returned as a single element in the list.
3. split() does not modify the original string.

See also  How Do I Compare Strings in Java?

Example:
python
text = “apple,banana”
parts = text.split(“;”)
print(parts) # Output: [‘apple,banana’]

The split() method is useful for parsing strings and processing text data efficiently!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x