Write a Python program to Split a given string on asterisk into several substrings and display each substring

1. Introduction

This blog post will showcase how to write a Python program that splits a given string on asterisks (*) into several substrings and displays each substring separately. This task is a common string manipulation operation in Python, illustrating the use of the split() method and string processing techniques.

2. Program Steps

1. Define a string with asterisks as separators.

2. Use the split() method to split the string into substrings based on the asterisk.

3. Iterate over the resulting list of substrings and display each one.

3. Code Program


def split_and_display(input_string):
    # Step 2: Split the string using the asterisk as a separator
    substrings = input_string.split('*')

    # Step 3: Iterate over the substrings and display each one
    for substring in substrings:
        print(substring)

# Step 1: Define a string with asterisks
input_str = "Python*is*a*great*language"
split_and_display(input_str)

Output:

Given the input string 'Python*is*a*great*language', the output will be:
Python
is
a
great
language

Explanation:

1. The function split_and_display takes input_string as an argument.

2. It uses the split('*') method to divide the string into a list of substrings, using the asterisk as the delimiter.

3. The function then iterates over the list of substrings. For each iteration, it prints the substring.

4. When the function is called with the string 'Pythonisagreatlanguage', it splits the string at each asterisk and prints each part on a new line.

This program effectively demonstrates how to split a string into substrings based on a specific delimiter in Python and how to process each substring individually.


Comments