How a button get selectedText and replace it with something?

Depending on your goal, maybe something like this will work for you as a pure Python solution (not tested):

text = editor.web.selectedText()
editor.note[editor.currentField] = text.replace('foo', 'bar')
editor.loadNoteKeepingFocus()

I think you have to use JavaScript if you want an accurate solution that actually only modifies selected text. Anki mostly only provides a wrap(before, after) JS function for wrapping selected text. You’ll need to get your hands dirty with DOM manipulations with JS for most cases.