Container Data Structures

Strings in Detail

Strings are basically lists of characters in Python. It is possible to access any character in the string using the index reference operator []  as in

course = "Cmpe150"

print(course[3])

which will output e, the character at position 3 (Pos. 0: 'C', Pos. 1: 'm', Pos. 2: 'p', Pos.3:'e', and so on).

The length, i.e. the number of characters in a string, can be obtained using the len() function as in

course = "Cmpe 150 \n \\"
print(course)

print(len(course))

len() function also counts any whitespace character included in the string. Keep in mind that each special character escaped by "\" as in "\n" or "\\" consists of a single character.

String members can be iterated in a for loop as in

course = "Cmpe 150 \n \\"

for character in course:
    print(character)

producing an output of

C
m
p
e
 
1
5
0
 


 
\

Note that the print() function inserts an additional new line character even for the "\n" in the string.

The in operator has an additional functionality to find out whether a string on the left hand side of the operator can be found in the string on the right hand side.

course = "Cmpe 150 "

if "150" in course:
    print("Course code matches 150")

The in operator can be negated by using the not operator as in

course = "Cmpe 150 "

if "250" not in course:
    print("Course code does not match 250")

The in operator returns a boolean value when used in an if clause. On the other hand, it is used for iteratively assigning values to a loop variable when used in a for loop.