+1 vote

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?

in Engine by (266 points)

1 Answer

+2 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:


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.

by (512 points)
selected by
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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.