Python Repeat Last N Characters of String N Times


  • Banned

    How to solve this question?

    Given a string and an integer n, return a string made of n repetitions of the last n characters of the string.
    You may assume that n is between 0 and the length of the string inclusive.
    For example if the inputs are “Punch” and 3, then the output should be “nchnchnch”.

    Thanks in advance!



  • Here is how I would approach it:

    Step 1)

    You can extract parts of any string using the following syntax

    string[ start_index_pos: end_index_pos: step_size]
    

    where string the name of the string variable and step_size is optional.

    You can use negative index numbers to determine starting index from the end instead of the front.
    So -1 is the last character. I think an example might illustrate this a little more clearly.

    str = "PYTHON"
    n = 2
    last_chars = str[-n:]
    

    would make last_chars equal to "ON"

    Step 2)

    The next step is to loop n time using a simple for loop and print out last_chars

    Let me know if you get stuck I can help further.



  • Here is how I would approach it:

    Step 1)

    You can extract parts of any string using the following syntax

    string[ start_index_pos: end_index_pos: step_size]
    

    where string the name of the string variable and step_size is optional.

    You can use negative index numbers to determine starting index from the end instead of the front.
    So -1 is the last character. I think an example might illustrate this a little more clearly.

    str = "PYTHON"
    n = 2
    last_chars = str[-n:]
    

    would make last_chars equal to "ON"

    Step 2)

    The next step is to loop n time using a simple for loop and print out last_chars

    Let me know if you get stuck I can help further.


Log in to reply