python split list code example

Example 1: separate a string in python

string = "A B C D"
string2 = "E-F-G-H"

# the split() function will return a list
stringlist = string.split()
# if you give no arguments, it will separate by whitespaces by default
# ["A", "B", "C", "D"]

stringlist2 = string2.split("-", 3)
# you can specify the maximum amount of elements the split() function will output
# ["E", "F", "G"]

Example 2: python split by list

def split(txt, seps):
    default_sep = seps[0]
    # we skip seps[0] because that's the default separator
    for sep in seps[1:]:
        txt = txt.replace(sep, default_sep)
    return [i.strip() for i in txt.split(default_sep)]


>>> split('ABC ; DEF123,GHI_JKL ; MN OP', (',', ';'))
['ABC', 'DEF123', 'GHI_JKL', 'MN OP']

Example 3: python split list

string = 'this is a python string'
wordList = string.split(' ')

Example 4: python split list

string = "this is a string" 		# Creates the string
splited_string = string.split(" ")	# Splits the string by spaces
print(splited_string) 				# Prints the list to the console
# Output: ['this', 'is', 'a', 'string']