Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python String split() function

Python string split() functions enable the user to split the list of strings. It’s very useful when we are working with CSV data.

String split() function syntax

string.split(separator, maxsplit)
  • separator: It basically acts as a delimiter and splits the string at the specified separator value.
  • maxsplit: It is a limit up to which the string can be split

Example: split() function

input= 'Engineering comprises of many courses.'

# splits at space
print(input.split())

Output:

['Engineering', 'comprises', 'of', 'many', 'courses.']

Example: Using “,” as a separator

input = "hello, Engineering and Medical, are two different disciplines"

result = input.split(",")

print(result)

Output:

['hello', 'Engineering and Medical', 'are two different disciplines']

Example: Setting maxsplit = value

input = "hello, Engineering and Medical, are two different disciplines"

# maxsplit = 1, returns a list with 2 elements..
i = input.split(",", 1)

print(i)

Output:

['hello', ' Engineering and Medical, are two different disciplines']

Multiline string split() function

input = 'Engineering discipline\nCommerce and Science\nYes and No'
result = input.split('\n')
for x in result:
    print(x)

Output:

Engineering discipline
Commerce and Science
Yes and No

Multi-Character separator in split() function

input = 'Engineering||Science||Commerce'
result = input.split('||')
print(result)

Output:

['Engineering', 'Science', 'Commerce']

str.split() function

Python String split() function can be used with class reference also. We have to pass the source string to split.

print(str.split('SAFA', sep='A'))
print(str.split('AMURA', sep='A', maxsplit=3))


CSV-String split() function

csv_input = input('Enter CSV Data\n')
csv_output1 = csv_input.split(sep=',')

print('\nList of inputs =', csv_output1)

Output:

Enter CSV Data
Android, Kotlin, Perl, Go

List of inputs = ['Android', ' Kotlin', ' Perl', ' Go']

Conclusion

Python string split() function is very useful in splitting delimiter based values into a list of strings.


References