Ask Question
23 June, 15:38

Write a Python program to replace at most 2 occurrences of space, comma, or dot with a colon. Hint: use re. sub (regex, "newtext", string, number_of_occurences)

+4
Answers (1)
  1. 23 June, 18:45
    0
    The "re" module in python provides various functions to perform complex string operations easily.

    For example, you can check whether a specific word exists in a given string or to replace it with some other word.

    Some of the functions in the re module are:

    re. findall

    re. search

    re. sub ()

    We are particularly interested in the re. sub () function, we can use this function to replace the occurrences of space, coma or dot with semicolon.

    Syntax:

    re. sub (pattern, replace, target_string, n).

    Where pattern = space, coma or dot

    replace = semicolon

    target_string = any string containing spaces, coma and dots

    n = number of times you want the replacement to be done

    Code:

    import re

    target_string = "Hello world, code, code."

    replace = ":"

    pattern = "[,.]"

    print (target_string)

    print (re. sub (pattern, replace, target_string, 2))

    Output:

    Hello world, code, code.

    Hello:world:code, code.

    It replaced the first white space and coma with semicolon, if we increase the n to 4 then the output is

    Hello:world:code:code:

    As expected, it replaced all of the space, coma, and dots with semicolons.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a Python program to replace at most 2 occurrences of space, comma, or dot with a colon. Hint: use re. sub (regex, "newtext", string, ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers