Lesson 5.3 · Write it
Tidy a product code
A functionPython or Java8 tests, 5 of them hidden
On a phone? Put the lines in order instead
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.
codecontains only English letters, digits and spaces. At least one character is not a space.- Remove every space, wherever it is.
- 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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)