Is it possible to insert a string in the middle of another string?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By kowid51384

For example, I’d like to turn “AppleOrange” into “AppXleOrange”. Can I insert a string in the middle of another string, or do I have to copy it into two different variables, erase some parts, and do something like this: print(varA + “X” + varB)?

:bust_in_silhouette: Reply From: andresTapa

Hi! i think you could try this:

var message: String = "AppleOrange"		# the message
var indx: int = message.find('O')		# we find the 'O' position
message = message.insert(indx,"Xle")	# we insert the substring 
										# at the tokken's position
print(message)							# AppleXleOrange

it worked for me. You can learn more in the String class documentation.

“message.insert()” was just what I was looking for, thanks!

Your answer is much more specific to my example than I was expecting, but I think that’s my fault, for posterity I was thinking something like this (inserting a string into another string after n number of characters):

message = "AppleOrange"
insert_message = "X"
insert_position = 3
final_message = message.insert(insert_position,insert_message)
print(final_message)

But thanks again for your help!

kowid51384 | 2022-07-05 19:19

happy to help, the important thing here that we all learned something. :smiley:

andresTapa | 2022-07-06 00:14