w3resource

Python string substring replacement

Python None Data Type: Exercise-10 with Solution

Write a Python function that replaces all occurrences of a substring in a string with another substring. Returns None if the original string is empty.

Sample Solution:

Code:

def replace_substr(original_string, old_substring, new_substring):
    if original_string:
        return original_string.replace(old_substring, new_substring)
    else:
        return None

def main():
    try:
        input_string = "Java Exercises!"
        old_substr = "Java"
        new_substr = "Python"
        
        result = replace_substr(input_string, old_substr, new_substr)
        
        if result is None:
            print("Original string is empty.")
        else:
            print("Original String:", input_string)
            print("New String:", result)
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Original String: Java Exercises!
New String: Python Exercises!
Original string is empty.

In the exercise above, the "replace_substr()" function checks if the original string is not blank. If it's not empty, it uses the 'replace' method to replace all occurrences of the 'old_substr' with the 'new_substr'. If the original string is empty, it returns 'None'. The "main()" function demonstrates the function's usage by providing a sample string and printing the initial and modified strings.

Flowchart:

Flowchart: Python string substring replacement.

Previous:Insert None between list elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.