How do nab a segment of a string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lavaduder
:warning: Old Version Published before Godot 3 was released.

I know in python i’d be able to do this by
stri = "dash" print(stri[1:3])

But if I try this in gdscript, it says expected ‘]’.
var text = "sapper" print(text[1:4])

Is as if the colon blocks the script reader from reading the whole thing. How do you grab a section of a string?

:bust_in_silhouette: Reply From: literalcitrus

Probably the easiest way to achieve this, though it’s not 100% identical to Python’s implementation, is to use the substr() function on the string. It differs to Python slicing because it takes the starting index and a length, rather than the starting and ending indices.

For your sapper example it would be:

print(text.substr(1,3))

Note that text[1:4] becomes text.substr(1,3) when using substr().

For completeness sake, to achieve the same effect as print(stri[i:]) you can use the right() function, and for print(stri[:i]) you can use the left() function.

All these functions are only available on the String class, GDScript doesn’t have arrays that are as powerful as Python lists unfortunately.