简体   繁体   中英

How to use re.sub to remove numbers

I'm trying to remove the numbers from my string, but keep the numbers that are in the middle. Right now my output for the code below is:

"This is a test numbers at end or beginning of a word should be deleted but not ones in the middle."

but I want it to be:

"This is a test numbers at end or beginning of a word should be deleted but not ones in the midd3le."

How should I do this?

String = "This is a test numbers33 at end or 333beginning of a word should be deleted but not ones in the midd3le."

s = re.sub("[\d]", "", String)

You can try this pattern:

String = "This is a test numbers33 at end or 333beginning of a word should be deleted but not ones in the midd3le."

s = re.sub(r"\b\d+|\d+\b", "", String)

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM