More on strings and functions#

String indexing and slicing#

We have already looked briefly at strings previously. Like tuples and lists, strings too are of Sequence type in Python, therefore they support slicing, membership operators, concatenation, replication and the other utility functions we mentioned in the Tuples section. Instead of data items, however, strings are composed of a sequence of characters. Fig. 8 below shows an example of the sequence of characters in the string “Hello World!” together with its index positions.

_images/string-indexes.png

Fig. 8 Indexes for str “Hello World!#

Thus, we can extract characters from a string as in the code below:

And we can slice a string as below:

_images/string-slicing.png

Fig. 9 String slicing.#

Strings are immutable#

Like tuples, since strings are immutable, one cannot change the contents of a character in a string. Trying to modify a character in a string will throw an error as shown below:

String utility functions and methods#

More useful functions and methods for strings are listed in Table 7. A list of all the String methods in Python can be found here.

Table 7 String utility functions#

Function

Description

len(s)

returns the length of the string s.

s.isnumeric()

returns True if s is a number.

s.lower()

returns s in lowercase.

s.upper()

returns s in uppercase.

s.count(sub, start, end)

returns the number of times sub is present in s from start to end position.

Exercise 5 (Joining strings)

Level:

Given a list of str objects defined as below:

words = ["keep", "calm", "and", "carry", "on"]

Join all the str objects together and separate them by a space into one str object and print it. The final string should have the following value: “keep calm and carry on”

Tip

Use the join() String method. Look at its documentation to see how this can be used.

Exercise 6 (Spliting strings)

Level:

In this exercise write code that counts and prints the number of words in the famous quote from Star Wars: “May the Force be with you”