Ask Question
30 November, 13:17

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)

+3
Answers (1)
  1. 30 November, 13:43
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers