how to make a text object have underlined text So i am using the code

T.text = 'sample text'


Where T is a text object. What I want is for part of the text to be underlined and the other part to remain plain. Can someone tell me how to make the word 'sample' underlined but have the word 'text' remain the way it is?
There are two ways to change the formatting, first is using operators to replicate the steps you would do by hand.

bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.font.move(type='LINE_BEGIN')
bpy.ops.font.move_select(type='NEXT_WORD')
bpy.ops.font.style_set(style='UNDERLINE', clear=false)
bpy.ops.object.mode_set(mode='OBJECT')


That should look obvious - move to the beginning of the line, move and select to the next word, then apply a style to the selected text.

The other way is to adjust the data that stores the formatting. A font object uses a TextCurve to store it's object data, the body and body_format properties are what you are interested in. body is the text string and body_format is a list of TextCharacterFormat which includes use_underline for each character in the body.

So to underline the first 6 characters of the active object -

for c in range(6):
    bpy.context.object.data.body_format[c].use_underline = True