Menu

String Manipulation

Loops and strings

A string is a sequence of characters, and each character sits at a numbered position called an index, starting at 0. A count-controlled loop can use those indexes as its counter, so the loop body works on one character at a time.

Visiting every character

A loop written as for i in range(0, len(s)): gives i the values 0, 1, 2 and so on up to len(s) - 1, which is every valid index. Inside the loop s[i] picks out the character at that index, so each character is visited exactly once. The end value of range() is not included, which is why writing len(s) is safe: the loop stops before the position that would be past the end of the string.

Counting characters that meet a condition

Set a total to 0 before the loop, then use an if inside the loop to test each character. When the test is true, add 1 to the total. For example, a row of seats marked "OOXXOXO" uses X for booked, so testing each character against "X" and adding 1 when it matches counts the booked seats. If capital and lowercase letters should count the same, store s = s.lower() first, so every character is compared in a consistent case.

seats = "OOXXOXO"
booked = 0
for i in range(0, len(seats)):
    if seats[i] == "X":
        booked = booked + 1
print("Booked seats:", booked)

Output:

Booked seats: 3

Building a new string

Start with an empty string, then join one character at a time by writing newText + s[i] and storing the answer back in newText. Each pass makes the new string one character longer. Choosing which characters to add lets you build a filtered string, such as keeping only the digits from a code.

To visit the characters in reverse, give range() a step of -1: range(len(s) - 1, -1, -1) counts down from the last index to 0. Adding each character to the end of the new string as you go puts them in that order, so the finished string is the original written backwards.

chosen = input("Enter a word: ")
secret = ""
for i in range(len(chosen) - 1, -1, -1):
    secret = secret + chosen[i]
print(secret)

Output when the user types garden:

Enter a word: garden
nedrag

Practise this