Back

Traversing a string

A common task in programming is working your way through a string, both forwards and backwards.

Q1. Get this code working:

1.    def forwards(anyWord):
2.        index = 0
3.        while index < len(anyWord):
4.            letter = anyWord[index]
5.            print(letter)
6.            index = index + 1
7.
8.    myWord = input("Please enter a word or phrase >>> ")
9.
10.  print("\n")
11.
12.  forwards(myWord)

13.  input("\n\nPress any key to quit >>> ")

Q2. Describe how this code works.

Q3. In addition to printing out each letter on a new line, modify the code to print out the length of the string entered with a message e.g.

The length of the string is 4

Q4. Modify the code so that the letters are all on the same line but separated by a tab e.g.

A     u     s     t     r     a     l     i     a

Q5. Define an extra function to print out your string letter by letter in reverse order. A first attempt at some pseudo-code might look like this ...

set your index to the length of the string
while length of your string > 0
    letter = your sting[index - 1]      #because we start counting from zero)
    print letter
    index = index - 1

Test it fully when you have written it. 

Q6. Using a FOR loop, print out the letters of the string "Telephone" one by one, each on a new line. You may need to look up a FOR loop works in Python and how to use 'in'.

Q7. You can always traverse a string using a for loop. Try this code:

my_string = 'Fish and chips'
for letter in my_string:
    print(letter)

Q8. Modify the code to allow the user to enter in any string when the program is run. Don't forget to fully test it.

Q9. Which of the following are valid variable names in Python? Change the variable letter in the lines for letter in my_string and print(letter) to these variable names and see if your predictions were correct:

_letter
__letter

LETTER
12344321

45letter
constant
while
a
????
toenails
LAPtop
Laptop????
laptop_

What are the rules you must obey for naming variables in Python?

Q10. Modify the print line in the code above using the following lines and see what happens:

print(letter, end ='')     #two single quotes together
print(letter, end =' ')    #two single quotes with a space between them
print(letter, end ='sunny')
print(letter, end ='sunny\n')
print(letter, end ='sunny\n\n')
print(letter, end ='sunny\t')
print(letter, end ='sunny\a')
print(letter, end ='sunny\a\n')
print(letter.upper(), end ='\asunny\n')
print(letter.lower(), end ='\asunny\n')

print('\a ', letter.upper(), end='sunny\n')

Back