39. Mask all but the last four
Receipts and account pages often show only the end of a long number: ############5616. The rest is hidden so that
someone looking over your shoulder can't read it.
Write a function mask(text) that takes a string and returns it with every character except the last four replaced
by #:
- Every character counts, spaces and punctuation included.
- A text of four characters or fewer is returned as it is: there is nothing to hide.
- An empty text gives an empty string
"".
Example 1
Input
text = "4556364607935616"Output
"############5616"Explanation16 characters: 12 hidden, the last 4 shown.
Example 2
Input
text = "Skippy"Output
"##ippy"ExplanationOnly the first 2 of 6 are hidden.
Example 3
Input
text = "abc"Output
"abc"ExplanationUnder 4 characters: nothing to hide.
Constraints
texthas 0 to 100 characters, of any kind.
Submit also runs 7 more tests you can't see.
Practises Strings (lesson 4).
- Negative indexes count from the end:
text[-4:]is the last four characters, or the whole text if it is shorter. "#" * 3is"###": multiplying a string repeats it. How many#do you need?len(text) - 4.- For a short text,
len(text) - 4is 0 or less, and"#" * -2is just"", so"#" * (len(text) - 4) + text[-4:]works for every length.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def mask(text):
"""Hide all but the last four characters of text.
text: str, any characters; may be empty
Returns: str, the same length, every character but the
last four replaced by "#"
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.