This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

Answer from ridgerunner on Stack Overflow
Discussions

Str.replace not working?
You probably just want this: updated['twitter_handle'] = updated['twitter_handle'].replace('?langen', '') More on reddit.com
🌐 r/learnpython
7
1
January 20, 2021
How do I incorporate &nbsp; in regular expressions ?
You can stick it in a string with hex escape codes. 160 would be '\xa0', if I can do math this late at night. See if your regex engine works if you just stick some of those in the literal. More on reddit.com
🌐 r/Python
13
10
June 18, 2014
How do you replace a character in a string with a single backslash?

r/learnpython is probably a better subreddit for these kinds of questions.

Having said that, your first example actually works, try:

print("apple".replace('l', '\\'))
More on reddit.com
🌐 r/Python
7
0
March 16, 2015
Code for removing brackets and their contents in Python. I'm sure someone might find a use for it.

Why not just use regex?

More on reddit.com
🌐 r/Python
10
0
June 16, 2015
🌐
Flexiple
flexiple.com › python › python-regex-replace
Python regex: How to search and replace strings | Flexiple - Flexiple
We need to replace the uppercase with the lowercase and vice versa. In order to do that, we will make two groups and then add a function for the replacement. ... To replace a string in Python, the regex sub() method is used.
🌐
Python documentation
docs.python.org › 3 › howto › regex.html
Regular expression HOWTO — Python 3.14.6 documentation
If the pattern isn’t found, string is returned unchanged. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences. Here’s a simple example of using the sub() method.
🌐
PYnative
pynative.com › home › python › regex › python regex replace pattern in a string using re.sub()
Python Regex Replace Pattern in a string using re.sub()
July 19, 2021 - import re # replacement function to convert uppercase letter to lowercase def convert_to_lower(match_obj): if match_obj.group() is not None: return match_obj.group().lower() # Original String str = "Emma LOves PINEAPPLE DEssert and COCONUT Ice Cream" # pass replacement function to re.sub() ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - Use the | operator to match multiple patterns. Each pattern may include special regex characters or literal substrings. This allows you to replace different substrings with the same string.
🌐
W3docs
w3docs.com › home › code snippets › python › python string.replace regular expression
Python string.replace regular expression | W3docs
Here's an example: ... Note that re.sub() is case-sensitive by default, so "The" remains unchanged. To match both cases, pass the re.IGNORECASE flag: re.sub("the", "a", string, flags=re.IGNORECASE).
Find elsewhere
🌐
Squash
squash.io › how-to-replace-regex-in-python
How To Replace Text with Regex In Python - Squash Labs
September 24, 2023 - In this example, the regex pattern [aeiou] matches any vowel in the input string. The occurrences of the vowels are replaced with asterisks using the re.sub() function. Related Article: How to Work with Encoding & Multiple Languages in Django · Another approach to replacing regex patterns in Python is by using regex groups and backreferences.
🌐
Index.dev
index.dev › blog › regex-advanced-string-replacement-python
Python Regex Replace: How to Replace Strings Using re Module
In this example, the pattern r"(\w+), (\w+)" captures the last name and first name separately. The replacement string r"\2 \1" refers to these captured groups, swapping their order.
🌐
Linux Hint
linuxhint.com › python_string_replacement
Python String Replacement using Pattern – Linux Hint
Some uses of the above-mentioned metacharacters with sub() method are shown in the following string replacement examples. If you know the exact string value that you want to search in the main string then you can use the searching string value as a pattern in sub() method. Create a python file with the following script. Here, the searching string value is ‘rainy’ and the replacing string value is ‘sunny’. #!/usr/bin/env python3 # Import regex module import re # Define a string orgStr = "It is a rainy day" # Replace the string repStr = re.sub("rainy", "sunny", orgStr) # Print the original string print("Original Text:", orgStr) # Print the replaced string print("Replaced Text:", repStr)
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python string tutorial › python regex replace
Python regex replace | Learn the Parameters of Python regex replace
May 13, 2024 - In this article, we are discussing ... with some specified patterns using regular expressions, so to do this, we have to use the sub() method....
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Dive into Python
diveintopython.org › home › learn python programming › regex in python
RegEx in Python: Match and Replace Basics with Examples
May 3, 2024 - It's particularly useful when you ... specific parts of the matched text. import re text = "2024 is the year of code" # Replace all instances of a digit sequence with 'XXXX' result = re.sub(r'\d+', 'XXXX', text) print(result) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-substituting-patterns-in-text-using-regex
Python - Substituting patterns in text using regex - GeeksforGeeks
July 12, 2025 - This example demonstrates the use of mentioned shorthand character classes for the substitution and preprocessing of text to get clean and error-free strings. Below is the implementation. ... # Python implementation of Substitution using # shorthand character class and preprocessing of text # importing regex module import re # Function to perform # operations on the strings def substitutor(): # list of strings S = ["2020 Olympic games have @# been cancelled", "Dr Vikram Sarabhai was +%--the ISRO’s first chairman", "Dr Abdul Kalam, the father of India's missile programme"] # loop to iterate e
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations — Python 3.14.6 ...
May 25, 2026 - However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a bytes pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string. Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.
🌐
Codedamn
codedamn.com › news › python
Python replace regex for searching and replacing strings
July 1, 2023 - In this example, the re.sub() function is used to replace all occurrences of 'codedamn' with 'CODEDAMN'. The output would be: Hello, CODEDAMN coders! Welcome to CODEDAMN community! The real power of regex comes with its ability to use special characters to construct search patterns, making it a vital tool for string manipulations in Python...
🌐
Medium
medium.com › @wepypixel › complete-python-regex-replace-guide-using-re-sub-pypixel-9b30b2604d7a
Complete Python Regex Replace Guide using re.sub() | PyPixel | by Stilest | Medium
December 8, 2023 - In our second example, we will remove all the whitespaces that are occurring in the string. Here’s the code for same: import re text = "Remove Whitespace from this text" trimmmed_text = re.sub(r"\s", "", text) print(trimmmed_text) # Output: RemoveWhitespacefromthistext · The “\s” pattern matches all the whitespaces in the text and replace the whitespace by closing it with “”. In case you need to extract a domain from a given , you can use regex to specify this pattern: r"^https?://(www\.?"
🌐
Real Python
realpython.com › replace-string-python
How to Replace a String in Python – Real Python
January 15, 2025 - In this tutorial, you'll learn how to remove or replace a string or substring. You'll go from the basic string method .replace() all the way up to a multi-layer regex pattern using the sub() function from Python's re module.
🌐
PythonTest
pythontest.com › python › regex-search-replace
Python regex Search and Replace Examples | PythonTest
I also may want to make a backup of example.txt first. We can all of those things, as I’ll show below. I think the most basic form of a search/replace script in python is something like this: import fileinput import re for line in fileinput.input(): line = re.sub('foo','bar', line.rstrip()) print(line) The fileinput module takes care of the stream verses filename input handling. The re (regex...
🌐
YouTube
youtube.com › automate with rakesh
#78 How to Search and Replace Strings in Python using Regex - YouTube
Learn how to use the regex in python to search and replace strings.Important Links:🔥 Visit Channel : https://www.youtube.com/c/AutomatewithRakesh🔥 To Su...
Published   July 16, 2022
Views   3K