Home > Net >  Remove text from string in python
Remove text from string in python

Time:04-29

I have a string and i need to remove few characters like this

text='abcd2345'
string = text.replace("cd", "") 

print(string)
ab2345

I need to remove the following two numbers in the string without specifying. how do i achieve it.

Output should be

ab45

CodePudding user response:

Since you have to specify a string then you can use regex:

import re

text = 'abcd2345'
string = re.sub('cd\d{2}', '', text)

Output:

'ab45'

How does it work?

It matches the string cd and any two numbers with the help of \d{2} followed by the string.

  • Related