1.7 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			1.7 KiB
		
	
	
	
	
	
	
	
title
| title | 
|---|
| String Split Method | 
The split() function is commonly used for string splitting in Python.
The split() method
Template: string.split(separator, maxsplit)
separator: The delimiter string. You split the string based on this character. For eg. it could be " ", ":", ";" etc
maxsplit: The number of times to split the string based on the separator. If not specified or -1, the string is split based on all occurrences of the separator
This method returns a list of substrings delimited by the separator
Examples
- Split string on space: " "
string = "freeCodeCamp is fun."
print(string.split(" "))
Output:
['freeCodeCamp', 'is', 'fun.']
- Split string on comma: ","
string = "freeCodeCamp,is fun, and informative"
print(string.split(","))
Output:
['freeCodeCamp', 'is fun', ' and informative']
- No separatorspecified
string = "freeCodeCamp is fun and informative"
print(string.split())
Output:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Note: If no separator is specified, then the string is stripped of all whitespace
string = "freeCodeCamp        is     fun and    informative"
print(string.split())
Output:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
- Split string using maxsplit. Here we split the string on " " twice:
string = "freeCodeCamp is fun and informative"
print(string.split(" ", 2))
Output:
['freeCodeCamp', 'is', 'fun and informative']
More Information
Check out the Python docs on string splitting