Hi,
I'm trying to work out this problem in my code where i am trying to replace a keyword with another word. The problem I am running into is that when the keyword is present inside of another word.
Eg,
"I'm trying to debug a problem but the debugger is not working"
I want to replace "debug" with "fix" but not have "debugger" replaced with "fixger"
Thanks.
Hazey 0 Newbie Poster
Recommended Answers
Jump to PostThis regular expression searches for "debug" not followed by an alphanumeric character or underscore
import re pat = re.compile(r"debug(?!\w)") sentence = "I'm trying to debug a problem but the debugger is not working" print pat.sub("fix", sentence)
However it wouldn't work for "I'm trying to debug a problem …
Jump to PostYou can use escape sequence \b to match exact words.
import re s = "I'm trying to debug a problem but the debugger is not working" target = 'debug' repl = 'fix' patt = re.compile(r'\b%s\b' % target) print patt.sub(repl, s)
Gribouillis has a very nice solution. I …
All 6 Replies
Gribouillis 1,391 Programming Explorer Team Colleague
Hazey 0 Newbie Poster
Gribouillis 1,391 Programming Explorer Team Colleague
Hazey 0 Newbie Poster
Gribouillis 1,391 Programming Explorer Team Colleague
bvdet 75 Junior Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.