Menu

String Manipulation

String length and indexing

A string is a sequence of characters, and each character has a numbered position called an index. Counting starts at 0, not 1, so the first character of "BeachParty" is B at index 0 and the second is e at index 1.

You select one character by putting its index in square brackets after the string or the variable holding it. If word = "BeachParty", then word[0] gives B and word[4] gives h.

word = "BeachParty"
print(word[0])
print(word[4])
print(len(word))
print(len(word) - 1)

Output:

B
h
10
9

Length and the last index

The len() function returns how many characters a string contains, as an integer. len("BeachParty") is 10. Every character counts, including spaces and symbols: "Order #27!" has 10 characters because the space, the hash and the exclamation mark are characters too.

Because counting starts at 0, the index of the last character is always the length minus 1. For "BeachParty" that is 10 - 1 = 9, which holds the final y. Valid indexes run from 0 up to the length minus 1; using an index equal to or greater than the length, such as word[10], causes an error.

Checking a length

You can use len() to test whether a piece of text is a suitable length. This chat message is only allowed up to 20 characters, so the program compares the length with 20 and prints a warning if it is over the limit. The same comparison checks that a password or code is long enough before it is accepted.

message = input("Enter your message: ")
if len(message) > 20:
    print("Message too long")
else:
    print("Message sent")

Output when the user types See you at the park after school:

Enter your message: See you at the park after school
Message too long

Practise this