# Can python be used to edit a Text Object?

That is, can python code replace, for example, a single letter in a Text Object or insert a letter or string into a Text Object.

Note that I'm not talking about replacing a Text Object with some updated string, such as, object.text = "new string". I'm thinking more about having access to the Text cursor (not the mouse cursor) and positioning it on some letter that I'd like to replace.

In other words, I'd like to have the same capability during BGE play that I have when altering a Text Object in the edit mode.

No this isnt supported, you have to replace the string with a new one each time.

• @dragonbyte In python itself string cannot be changed, they are immutable. You can use several python functions for strings though. – Vader Mar 27 '14 at 16:22

As ideasman42 pointed out, you must replace it with a new string since strings are immutable in Python. But here's a workaround.

Delete single character

This will delete the third character

cursor = 2
ob = bpy.context.scene.objects['Text']
text = ob.data.body
ob.data.body = text[:cursor] + text[cursor+1:]


where I've used slicing.

Insert single character

This will insert 'z' after second character

cursor = 2
new_char = 'z'
ob = bpy.context.scene.objects['Text']
text = ob.data.body
ob.data.body = text[:cursor] + new_char + text[cursor:]


It's possible using operators. Here's a simple example,

import bpy
bpy.ops.object.editmode_toggle()
bpy.ops.font.move(type='PREVIOUS_CHARACTER')
bpy.ops.font.delete(type='PREVIOUS_OR_SELECTION')
bpy.ops.font.text_insert(text="s", accent=False)
bpy.ops.font.move(type='NEXT_CHARACTER')
bpy.ops.object.editmode_toggle()


Running this on the default text object changes "Text" to "Test". Edit: I just saw this is for the game engine, I'm not sure if this code will work there.

Since you are working in the BGE, may I suggest:

from bge import logic, events

def editText(cursorPos):
own = logic.getCurrentController().owner

txt = list(own['Text'])

if (logic.keyboard[events.BACKSPACEKEY] == logic.KX_INPUT_JUST_ACTIVATED):
txt.pop(cursorPos)
else:
txt[cursorPos] = events.EventToCharacter(logic.keyboard[0], False)

####
# This text block will only change characters of the string in a certain position.
# Other than that you will need to do some more complex coding.