String Operations

We have seen enough operations on numbers, but despite computers are numerical (or digital) machines, they also do much work with text (even for preparing this page, of course, computer was needed). So let's learn a few most typical operations on text strings.

Most of such operations work on variables, which contain text, rather on, say, bare text literals. For example to get the length of the text string we use :len() function, like this:

s = 'What a Wonderful World!'
print(s:len())

This code results in 23. If you count characters (including spaces and exclamation mark, but not the surrounding quotes, of course - you'll see it is exact value!

As about the syntax with colon (:) and function name following some variable - we'll discuss it somewhere later. In short, it regards s as an "object" and len - the method of this object. As if we tell "variable s, go on and report your length yourself!"

Case conversion

Two handy functions to change lower letters to upper and vice versa. Try these yourself, it looks simple:

name = 'Gay Clown'
print(name:lower())
print(name:upper())

String Repeat

Funny function, though rarely needed, duplicates the same string several times. May be useful for creating shapes:

x = '-=0=-'
print(x:rep(10))

Substring

This one is extremely useful: it allows breaking string in parts or even work with individual characters:

word = 'unhappiness'
print(word:sub(3))

With single numeric argument :sub returns part of string starting from the given position. I.e. from the 3rd letter, so it would become happiness. It is also possible to supply second argument, telling "to what position" the substring should be taken, for example:

phrase = 'Good Girls Giggle'
print(phrase:sub(6,10))         -- should print "Girls"

Both indices also could be negative, which means counting from end. Experiment with those on your own please.

Exercises

Try solving these string-related problems on our site: