Strings

Strings provide a way to store text data (words) in variables, and through them, perform operations on that text.

string = "test"
text = "more words"

# Empty string, which can be added to later
more_text = ""

more_text += "wind"
more_text += "storm"

more_text will contain "windstorm", as more_text now contains "wind" + "storm" which acts in an intuitive sort of manner; the words are concatenated together.

To transform other kinds of data into strings, use str(). Note that when used on other kinds of sequences (Lists, Tuples, etc), str() returns a string containing that sequence, rather than a string containing the contents of that sequence.

String Slicing

Strings can also be 'sliced', which is difficult to explain in words:

string = "thunderstorm!"

string[1:4] will contain "hun" — letters 1-3.

string[-1:] will contain "!" — the last letter in the string.

string[-5:] will contain "torm!" — the last 5 letters in the string.

string[:-1] will contain "thunderstorm" — the string but with the last letter removed.

string[:-5] will contain "thunders" — the string but with the last 5 letters removed.

string[::2] will contain "tudrtr!" — the string but with every other letter removed.

string[::-1] will contain "!mrotsrednuht" — the string, but backwards.

It is likely evident that slicing is a very powerful tool, though a tad bit unintuitive. Slicing is actually a part of the subscripting syntax, and isn't unique to Strings; meaning that Lists and Tuples can also be sliced, although there may be fewer situations in which slicing is useful for other data types.

String Methods

For a full list of methods relating to the String data type, see https://docs.python.org/3/library/stdtypes.html#str.

lower

print("abc".upper())
print("ABC".lower())
ABC
abc

endswith

print("hurray!".endswith('!'))
True

isalpha

print("word".isalpha())
True

isnumeric

print("12345".isnumeric())
True

join

join is a particularly important String method, because it allows other sequences to be transformed and concatenated into strings. For instance:

list1 = ['a', 'b', 'c']
string1 = "".join(list1)

string1 now contains "abc".

join takes the first string provided and concatenates each string in the list of strings provided together, putting the first string inbetween each of them.

words = ["There is a place", "over there", "with mushrooms"]
inter = " - "
inter.join(words)
"There is a place - over there - with mushrooms"

Effectively, this means that any List method can also be used on a string, by transforming the string into a list with list(), and then retransforming the list back into a string using "".join().

Of course, this can get a little bit ridiculous, and some times there is an objectively better way to do things.

word_to_reverse = "university"
reversed_word = ''.join(list(reversed(list(word_to_reverse))))

Yes, reversed_word will now contain "ytisrevinu", but string slicing is much easier!

reversed_word = [::-1]