Python: Replace all but the last five characters of a given string into "*" and returns the new masked string
Mask All But Last Five Characters
Write a Python program that replaces all but the last five characters of a string with "*" and returns the modified string.
Sample Solution:
Python Code:
# Define a function named new_string that takes a string (str1) as an argument.
def new_string(str1):
# Create a new string composed of '*' repeated (len(str1) - 5) times, followed by the last 5 characters of the original string.
return '*' * (len(str1) - 5) + str1[-5:]
# Test the function with different strings and print the results.
# Test case 1
text = "kdi39323swe"
# Print the original string.
print("Original String: ", text)
# Print the new string generated by the function.
print("new string: ", new_string(text))
# Test case 2
text = "12345abcdef"
# Print the original string.
print("\nOriginal String: ", text)
# Print the new string generated by the function.
print("new string: ", new_string(text))
# Test case 3
text = "12345"
# Print the original string.
print("\nOriginal String: ", text)
# Print the new string generated by the function.
print("new string: ", new_string(text))
Sample Output:
Original String: kdi39323swe new string: ******23swe Original String: 12345abcdef new string: ******bcdef Original String: 12345 new string: 12345
Explanation:
Here is a breakdown of the above Python code:
- Function definition:
- The code defines a function named "new_string()" that takes a string (str1) as an argument.
- String Composition:
- The function creates a new string by concatenating '*' repeated (len(str1) - 5) times and the last 5 characters of the original string (str1[-5:]).
- Test cases:
- The function is tested with different strings, and the original strings along with the new strings are printed.
Visual Presentation:
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to compute the sum of the three lowest positive numbers from a given list of numbers.
Next: Write a Python program to count the number of arguments in a given function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics