Is it possible to edit the selected text via Python in the text editor?
Here is an example of a script that makes the currently selected piece of text uppercase. So the main thing here is the Text object of the space data which also has some other attributes you can use. The SpaceTextEditor might also have some usefull functions.
import bpy
text = bpy.context.space_data.text
fschar = text.current_character
fsline = text.current_line_index
fechar = text.select_end_character
feline = text.select_end_line_index

# The end and start lines and characters can be switched
# depending on the direction in which the text was selected
schar = min(fschar,fechar)
echar = max(fschar,fechar)
sline = min(fsline,feline)
eline = max(fsline,feline)

original_text = text.as_string()
lines = original_text.split(&quot;\n&quot;)

for line in range(sline, eline + 1):
    cur_line = lines[line]
    
    start_char = 0
    end_char = len(cur_line)
    
    if line == sline:
        start_char = schar
        
    if line == eline:
        end_char = echar
    
    # Uppercase the selected part of this line
    new_line = &quot;&quot;.join((cur_line[:start_char], cur_line[start_char:end_char].upper(), cur_line[end_char:]))
    lines[line] = new_line
    
new_text = &quot;\n&quot;.join(lines)

text.from_string(new_text)