0 votes

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?

asked Jan 14, 2018 in Engine by lavaduder (263 points)

1 Answer

0 votes
Best answer

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.

answered Jan 14, 2018 by literalcitrus (486 points)
selected Jan 21, 2018 by lavaduder
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.