The split() method splits a string by space in Python. You can use any separator like a comma, a hyphen, etc, the default separator is any space.
string.split(separator, maxsplit)
Note: Separator and max split are optional parameters.
The split()
method splits the string at each whitespace character (space, tab, newline, etc.) and returns a list of the resulting substrings. By default, if no argument is provided, it splits at any whitespace character.
You can also provide a specific separator as an argument to split()
, for example my_string.split(',')
to split the string at commas instead of spaces.
Example Split string on whitespace in Python
A simple example code split a string into a list.
txt = "Welcome to the Eyehunts"
x = txt.split()
print(x)
Output:
Another example
split string by single space
str = '63 41 92 81 69 70'
# split string by single space
chunks = str.split(' ')
print(chunks)
Output: [’63’, ’41’, ’92’, ’81’, ’69’, ’70’]
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.