how to parse a string in python 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: split string python

string = 'James Smith Bond'
x = string.split(' ') #Splits every ' ' (space) in the string to a list
# x = ['James','Smith','Bond']
print('The name is',x[-1],',',x[0],x[-1])

Example 3: python parse string

msg = "hi#my#name#is#alon"
msg = msg.split("#")
print(msg)
#output: ["hi", "my", "name", "is", "alon"]

Example 4: parsing text in python

my_string = 'Names: Romeo, Juliet'

# split the string at ':'
step_0 = my_string.split(':')

# get the first slice of the list
step_1 = step_0[1]

# split the string at ','
step_2 = step_1.split(',')

# strip leading and trailing edge spaces of each item of the list 
step_3 = [name.strip() for name in step_2]

# do all the above operations in one go
one_go = [name.strip() for name in my_string.split(':')[1].split(',')]

for idx, item in enumerate([step_0, step_1, step_2, step_3]):
    print("Step {}: {}".format(idx, item))

print("Final result in one go: {}".format(one_go))