How to apply a material to a selection in Text using Python The Blender documentation explains how to apply multiple materials to various selections in Text:




  For example, to create Fig. Red Green Blue. you would need to create three separate materials and three separate material indices. Each word would be assigned a Material index by selecting the characters for each word and clicking the Assign button. Fig. Red Green Blue. is still one single Text object.


When accessing the text using a Python script, we can see its contents as a string through the following command:

object.data.body


However, it is not clear to me how we could mark substrings and assign materials to them. Do we need to macro the operations (select a range, assign material, repeat) as if we were doing this through the UI? Is there a more streamlined API?

Is this achievable through a script at all?
The following script will cycle through all text objects and for each word (separated by space) assign a material slot index to the word incrementing the material slot through all available slots resetting to index 0 if there are more words than material slots.
Written &amp; tested on blender 2.79

import bpy

texts = [obj for obj in bpy.data.objects if obj.type == 'FONT']

bpy.ops.mode_select
for txt in texts:
    me = txt.data.body
    mats = txt.material_slots
    ind = 0
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.font.move(type='LINE_BEGIN')
    for word in me.split():
        bpy.ops.font.move_select(type='NEXT_WORD')
        bpy.context.object.active_material_index = ind
        bpy.ops.object.material_slot_assign()
        if ind &lt; len(mats):
            ind += 1
        else:
            ind = 0
        bpy.ops.font.move(type='NEXT_CHARACTER')
    bpy.ops.object.mode_set(mode='OBJECT')