BYU logo Computer Science

To start this guide, download this zip file.

Practice with strings

Following are some practice problems with strings and substrings.

Fruits

For this problem, write a program that asks you to enter a list of fruits. If you enter a fruit that has already been given, the program should say “You already said that.” The program should ignore casing (uppercase vs lowercase), so “Banana” is the same as “banana”.

Once 10 unique fruits have been entered, print “Way to go!” and end the program. Here is an example of input and output for this program:

Fruit: pear
Fruit: apple
Fruit: pear
You already said that.
Fruit: kiwi
Fruit: banana
Fruit: pear
You already said that.
Fruit: apple
You already said that.
Fruit: orange
Fruit: lemon
Fruit: lime
Fruit: cherry
Fruit: orange
You already said that.
Fruit: guava
Fruit: plum
Way to go!

Planning

Work with a friend to write this code. You can find starter code in fruits.py. Try drawing a flow chart.

work with a friend to solve this problem

Here is a flow chart that shows a solution to this problem:

while not 10 fruits, get a fruit, check if it is already in the list, append if not

Notice that we are careful to lowercase the fruit a person enters. This is needed so that Banana, banana, and BaNAnA are all treated the same.

Writing code

Try translating this flow chart into code on your own.

come back when you are done

Below is code that corresponds to the flow chart, with comments showing the relevant piece of the flow chart.

def main():
    # make an empty list
    fruits = []
    # do we have 10 fruits yet?
    while len(fruits) < 10:
        # get a fruit and lowercase it
        fruit = input('Fruit: ').lower()
        # already in the list?
        if fruit in fruits:
            # you already said that
            print('You already said that.')
        else:
            # append to the list
            fruits.append(fruit)
    # way to go!
    print('Way to go!')

You should be able to run this code and get something like the example shown above.

Organized

Write a program that “organizes” the things you type into it. “Organized” text means that all the characters are reordered to this sequence:

  • lowercase letters
  • uppercase letters
  • digits
  • everything else
  • whitespace is removed

Here is an example of input and output for this program:

Text: Hello, what is your name?
ellowhatisyournameH,?
Text: BYU is my favorite school!
ismyfavoriteschoolBYU!
Text: 3.14159 is a loose approx. for PI.
isalooseapproxforPI314159...
Text:

Planning

Work with a friend to write this code. You can find starter code in organized.py. Try drawing a flow chart.

work with a friend to solve this problem

Here is a flow chart that shows a solution to this problem:

get string, end if empty, otherwise organize it and then print it

This leaves out a lot of details! But this is how you should start — do the big picture first, and then fill in the details.

Writing code

Since this flow chart is so simple, it is easy to turn it into code:

def main():
    while True:
        text = input('Text: ')
        if text == '':
            break
        print(organize(text))

We have put all the details of organizing the text into one function — organize().

Planning the next steps

Now we need a flow chart for organizing a string of text. If you haven’t done this piece yet, work with a friend to draw this out.

work with a friend to solve this problem

Here is one way to do this:

Go through the characters one by one and append a character of each type to a separate variable

A few important notes:

  • We are going to keep a variable that stores a string of lowercase letters, another one for uppercase letters, one for digits, and one for all other characters.

  • We are going to loop through the characters one at a time and then append each character to the appropriate variable. The blue box is illustrating a for loop.

  • We ignore spaces.

  • At the end, we can concatenate all the string variables together to get the final result.

Writing more code

Try translating this flow chart into code on your own. You are trying to write the organize() function.

come back when you are done

OK, here is a good solution:

def organize(text):
    lowers = ''
    uppers = ''
    digits = ''
    others = ''
    for c in text:
        if c.islower():
            lowers += c
        elif c.isupper():
            uppers += c
        elif c.isdigit():
            digits += c
        elif c.isspace():
            pass
        else:
            others += c

    return lowers + uppers + digits + others

This is pretty simple code that follows the flow chart. We set up variables for each type of character, then we loop through all the characters and add them to the appropriate variable. We skip spaces. At the end, we return the concatenation of all the string variables.

You should be able to run this code and get something like the example shown above.

Word swap

Write a program that asks a person to enter a phrase, then two words or substrings to swap. Then swap the two words and print the result.

Here is some example input and output:

Phrase: It's raining cats and dogs.
Word 1: cats
Word 2: dogs
It's raining dogs and cats.
Phrase: Do you like where you live?
Word 1: ke
Word 2: ve
Do you live where you like?
Phrase:

Planning

Work with a friend to write this code. You can find starter code in word_swap.py. Try drawing a flow chart.

work with a friend to solve this problem

Here is a flow chart that shows a solution to this problem:

get a phrase, if empty exit, otherwise get two words, swap, and print

Hopefully you are getting the hang of this! Using a flow chart is a great way to organize your thoughts before you begin to code.

Writing code

Try translating this flow chart into code on your own.

come back when you are done

Below is code that corresponds to the flow chart:

def main():
    while True:
        text = input('Phrase: ')
        if text == '':
            break
        word1 = input('Word 1: ')
        word2 = input('Word 2: ')
        print(swap(text, word1, word2))

As with the previous problem, we put all the work in a separate function, swap().

Swapping

Now comes the tricky part. How do we swap? A simple, but wrong way to to do this is below:

def swap(text, word1, word2):
    text = text.replace(word1, word2)
    text = text.replace(word2, word1)
    return text

What will happen if we have the phrase It's raining cats and dogs. and then we want to swap cats and dogs? We will first replace cats with dogs and get: It's raining dogs and dogs. Then we will replace dogs with cats and get: It's raining cats and cats. Not good!

We have to instead do this:

  • replace word1 with a special symbol, e.g. @@@@
  • replace word2 with word1
  • replace @@@@ with word2

If we do this, we will get these strings:

  • It's raining @@@@ and dogs.
  • It's raining @@@@ and cats.
  • It's raining dogs and cats.

Here is the code:

def swap(text, word1, word2):
    symbol = '@@@@'
    text = text.replace(word1, symbol)
    text = text.replace(word2, word1)
    text = text.replace(symbol, word2)
    return text

If you run this code, you should be able to see output like above.

Calling replace multiple times

It turns out that we can rewrite the swap function above as:

def swap(text, word1, word2):
    symbol = '@@@@'
    return text.replace(word1, symbol).replace(word2, word1).replace(symbol, word2)

Why is this?

When you call replace(), the syntax is as follows:

string functions

It turns out that replace() returns a new string. So this means you can call it repeatedly:

string multiple functions

text = 'Yesterday I read an amazing book.'
new_text = text.replace('amazing', 'intriguing').replace('Yesterday', 'Today')
print(new_text)

This prints:

Today I read an intriguing book.

This works for any string function:

text = 'Yesterday I read an amazing book.'
new_text = text.replace('amazing', 'intriguing').replace('Yesterday', 'Today').upper()
print(new_text)

This prints:

TODAY I READ AN INTRIGUING BOOK.

Returning to our swap() function:

def swap(text, word1, word2):
    symbol = '@@@@'
    return text.replace(word1, symbol).replace(word2, word1).replace(symbol, word2)

Now you can see that we can chain together three calls to replace() and then return the final result, all in one step.

fabulous