Logo
/
Programming
/
Python Course
/

Traversing Strings

Python: Traversing Strings

Loops are used to work with strings as well as numbers. For example, you can get a specific character by its index, and also form strings in loops.

Below is some sample code that prints the letters of each word on a separate line:

def print_name_by_symbol(name):
    i = 0
    # This check will run until the end of the string,
    # including the last character. Its index is `length - 1`.
    while i < len(name):
        # Accessing the symbol by its index
        print(name[i])
        i += 1

name = 'Arya'
print_name_by_symbol(name)
# => 'A'
# => 'r'
# => 'y'
# => 'a'

The main thing in this code is to put the proper condition in while. This can be done in two ways: i < len(name) or i <= len(name) - 1 - they'll both give the same result.

Instructions

Write the function mask_card_number(), which hides a bank card number. The function should replace every character in the string with *, except for the last four.

mask_card_number("1234567812345678")  # "************5678"
mask_card_number("12345678")          # "****5678"

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Found a bug? Have something to add? Pull requests are welcome!