
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to enclose pattern into bold tag in Python?n
Suppose we have a text and a list of strings called patterns, we have to define an embolden function where all substrings in text that match any string in the given patterns are wrapped in and tags. If any two patterns are adjacent or overlap, they should be merged into one tag.
So, if the input is like text = "thisissampleline" patterns = ["this", "issam", "sample"], then the output will be "a<b>bc</b>d<b>ef</b>g", as bc and ef match the text and are wrapped in <b> and </b> tags.
To solve this, we will follow these steps
n := size of text
bold := a list of size n, and fill with False values
for i in range 0 to n, do
for each p in patterns, do
if substring of text[from index i to end] is starts with p, then
for j in range 0 to size of p, do
bold[i + j] := True
ans := blank string
for i in range 0 to n, do
if bold[i] and (i is same as 0 or bold[i - 1] is false) , then
ans := ans concatente "<b>"
ans := ans + text[i]
if bold[i] and (i is same as n - 1 or bold[i + 1] is false) , then
ans := ans concatenate "</b>"
return ans
Let us see the following implementation to get better understanding
Example
class Solution: def solve(self, text, patterns): n = len(text) bold = [False] * n for i in range(n): for p in patterns: if text[i:].startswith(p): for j in range(len(p)): bold[i + j] = True ans = "" for i in range(n): if bold[i] and (i == 0 or not bold[i - 1]): ans += "" ans += text[i] if bold[i] and (i == n - 1 or not bold[i + 1]): ans += "" return ans ob = Solution() text = "thisissampleline" patterns = ["this", "ssam", "sample"] print(ob.solve(text, patterns))
Input
"thisissampleline", ["this", "ssam", "sample"]
Output
<b>this</b>i<b>ssample</b>line
- Related Articles
- Add Bold Tag in String in C++
- Python Program to print the pattern ‘G’
- Python program to print matrix in a snake pattern
- Python Program to Print an Inverted Star Pattern
- Python program to print rangoli pattern using alphabets
- How to correctly enclose subquery in MySQL?
- How to set the font style to Bold in Python Plotly?
- How to use Bold & Non-Bold Text In A Single UILabel in iOS/iPhone?
- Python program to show diamond pattern with 2n-1 lines
- How to print pattern in Python?
- Python program to convert Set into Tuple and Tuple into Set
- Program to print Interesting pattern in C++
- Program to print Kite Pattern in C++
- Program to print number pattern in C
- Program to print Diamond Pattern in C
