Answers for "python string parsing"

27

separate a string in python

foo = "A B C D"
bar = "E-F-G-H"

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

bar_list = bar.split("-", 3)
# you can specify the maximum amount of elements the split() function will output
# ["E", "F", "G"]
Posted by: Guest on May-05-2020
2

python parse string

msg = "hi#my#name#is#alon"
msg = msg.split("#")
print(msg)
#output: ["hi", "my", "name", "is", "alon"]
Posted by: Guest on May-09-2020
0

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))
Posted by: Guest on August-07-2020

Python Answers by Framework

Browse Popular Code Answers by Language