Split a String into Sub-string and Parse in Python


If you have a string that you want to parse, but there is a need to split it first, to achieve this we can make use of the split function with the delimiter and then collect the sub-strings as a list and parse it.

let's see how this can be done step-by-step,


Step 1: The String to Parse
string_to_parse = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

Step 2: Split the String using split()
split_string = string_to_parse.split(",")

Step 3: Parse the list of strings
parsed_list = []

for substr in split_list:
    parsed_value = num2words(int(substr))
    parsed_list.append(parsed_value)

Step 4: Print the result
print(parsed_list)

['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']


Complete code example:

from num2words import num2words

# Step 1: The String to Parse
string_to_parse = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"

# Step 2: Split the String using split()
split_list = string_to_parse.split(",")

# Step 3: Parse the list of strings
parsed_list = []

for substr in split_list:
    parsed_value = num2words(int(substr))
    parsed_list.append(parsed_value)

# Step 4: Print the result
print(parsed_list)

For this example we have made use of num2words library to convert numbers to equivalent words while parsing.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap