Skip to content
ExamSpine

Lesson 5.3

Search, replace, change case

Part 5: Text, lists, stacks and queuesReading, about 5 min4 exercises in this lesson

Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.

Search, replace and change case

By the end of this you will be able to change the case of a text value, find where one piece of text sits inside another, and replace one piece with another.

Each of these jobs is a single call. One rule catches almost everyone once: changing case and replacing give back a new text value, and the text you started with does not change.

Changing case

word = "Planet"
print(word.upper())
print(word.lower())
print(word)
public static void main(String[] args) {
    String word = "Planet";
    System.out.println(word.toUpperCase());
    System.out.println(word.toLowerCase());
    System.out.println(word);
}

When it runs:

PLANET
planet
Planet

The last line shows the rule: word is still Planet.

Changing case is how a program compares two text values without caring about capitals. Put both in the same case first, then compare. "Quit" and "QUIT" are different, but in lower case both are quit.

Searching

There are two questions you can ask: is it in there, and where. The first is written in in Python and contains in Java.

word = "Planet"
print("an" in word)
print(word.find("an"))
print(word.find("x"))
public static void main(String[] args) {
    String word = "Planet";
    System.out.println(word.contains("an"));
    System.out.println(word.indexOf("an"));
    System.out.println(word.indexOf("x"));
}

The first line printed is True in Python and true in Java. Then:

2
-1

find in Python and indexOf in Java give the index where the piece first starts. an starts at index 2 of Planet. When the piece is not there, the answer is -1. Indexes are counted from 0, so -1 cannot be where anything starts. It can only mean "not found".

A common mistake: using the answer as an index without checking for -1. Java stops with an error. Python does not: it takes -1 to mean the last index, and carries on with the wrong value. If the piece might not be there, test for -1 first.

Replacing

name = "banana"
name.replace("a", "o")
print(name)
name = name.replace("a", "o")
print(name)
public static void main(String[] args) {
    String name = "banana";
    name.replace("a", "o");
    System.out.println(name);
    name = name.replace("a", "o");
    System.out.println(name);
}

When it runs:

banana
bonono

replace swaps every copy of the first piece for the second. The first call stands on a line by itself. It makes the new text and then throws it away, because nothing keeps it, so the first thing printed is still banana. name only changes on the line that stores the result back in name.

A common mistake, and the one to remember from this lesson: replacing, or changing case, and not keeping what comes back. If a text value seems to ignore your change, check that the result is stored or used.

Now try it yourself on the questions below.

Exercise 5.3.1 · Trace itTrace: case and replace

Complete the trace table for this Python code. word.upper() gives back the text in capital letters. word.replace("o", "a") gives back the text with each o changed to an a. Then answer the question below the table. [4]

Line 1: word = "robot"
Line 2: loud = word.upper()
Line 3: word.replace("o", "a")
Line 4: print(loud)
Line 5: print(word)

Fill in one row each time a line changes word or loud, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Python shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.

Rowwordloudoutput
1
2
3
4

Exercise 5.3.1 · Trace itTrace: case and replace (Java)

Complete the trace table for this Java code. word.toUpperCase() gives back the text in capital letters. word.replace("o", "a") gives back the text with each o changed to an a. Then answer the question below the table. [4]

Line 1: String word = "robot";
Line 2: String loud = word.toUpperCase();
Line 3: word.replace("o", "a");
Line 4: System.out.println(loud);
Line 5: System.out.println(word);

Fill in one row each time a line changes word or loud, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Java shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.

Rowwordloudoutput
1
2
3
4

Exercise 5.3.25.3.2 · Write itSame word

Write a function that returns whether two words are the same when upper and lower case are ignored.

  1. Each word contains only English letters, and has at least one letter.
  2. Two words are the same when they have the same letters in the same order. The case of each letter does not matter.
  3. Return True or False (true or false in Java).

Only the value your function returns is checked.

def same_word(first: str, second: str) -> bool

Examples

Your function is tested on 14 cases: the 3 examples below, and 11 hidden ones that check the rules above.

  • same_word("Quit", "qUIT") should return True: the same letters, with capitals in different places (rule 2)
  • same_word("plays", "play") should return False: different words, the second is the start of the first (rule 2)
  • same_word("go", "goes") should return False: different words, the first is the start of the second (rule 2)

public static boolean sameWord(String first, String second)

Checking whether Java answers can run here.

Examples

Your function is tested on 14 cases: the 3 examples below, and 11 hidden ones that check the rules above.

  • sameWord("Quit", "qUIT") should return true: the same letters, with capitals in different places (rule 2)
  • sameWord("plays", "play") should return false: different words, the second is the start of the first (rule 2)
  • sameWord("go", "goes") should return false: different words, the first is the start of the second (rule 2)
solution.pySolution.java

Exercise 5.3.35.3.3 · Write itBefore the @

Write a function that returns the part of an email address that comes before the @.

  1. The address contains exactly one @. Every other character is an English letter, a digit, a dot or a hyphen.
  2. There is at least one character before the @.
  3. Return every character before the @, and nothing else. The @ itself is not included.

Only the value your function returns is checked.

def username(address: str) -> str

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • username("mia@example.org") should return "mia": three characters before the @ (rule 3)
  • username("a@b.example") should return "a": one character before the @, the fewest allowed (rule 2)
  • username("sam.lee@example.net") should return "sam.lee": a dot before the @ is part of the answer

public static String username(String address)

Checking whether Java answers can run here.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • username("mia@example.org") should return "mia": three characters before the @ (rule 3)
  • username("a@b.example") should return "a": one character before the @, the fewest allowed (rule 2)
  • username("sam.lee@example.net") should return "sam.lee": a dot before the @ is part of the answer
solution.pySolution.java

Exercise 5.3.45.3.4 · Write itTidy a product code

A product code is typed by hand, so it arrives with spaces in it and in any mix of upper and lower case. Write a function that returns the code tidied up.

  1. code contains only English letters, digits and spaces. At least one character is not a space.
  2. Remove every space, wherever it is.
  3. Change every letter to upper case.

Only the value your function returns is checked.

def tidy_code(code: str) -> str

Examples

Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.

  • tidy_code("ab 12 cd") should return "AB12CD": two spaces removed and four letters changed (rules 2 and 3)
  • tidy_code("XY7") should return "XY7": already tidy, so it comes back the same
  • tidy_code(" q 4 ") should return "Q4": spaces at the start and the end are removed too (rule 2)

public static String tidyCode(String code)

Checking whether Java answers can run here.

Examples

Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.

  • tidyCode("ab 12 cd") should return "AB12CD": two spaces removed and four letters changed (rules 2 and 3)
  • tidyCode("XY7") should return "XY7": already tidy, so it comes back the same
  • tidyCode(" q 4 ") should return "Q4": spaces at the start and the end are removed too (rule 2)
solution.pySolution.java