python - Replacing words tagged by #word# within a string -


i want search , replace words between 2 # marks.

the text random (users add it).

example:

text = "hello #word1# #word2# thanks!" 

i need cut 2 words between # (word1 , word2) , change words title case - .title().

desired output:

"hello #word1# #word2# thanks!" 

you can using regular expression:

import re  text = 'hello #word1# #word2# thanks!' print re.sub('#(\w+)#', lambda m:m.group(1).title(), text) 

output:

hello word1 word2 thanks!

edit

if want retain bounding # characters, use noncapturing expressions:

print re.sub('(?<=#)(\w+)(?=#)', lambda m:m.group(1).title(), text) 

output:

hello #word1# #word2# thanks!


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -