27.8k views
0 votes
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)

1 Answer

1 vote

Explanation:

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.

User Morph
by
5.5k points