w3resource

Python: Get a string made of 4 copies of the last two characters of a specified string


Repeat last 2 chars of a string 4 times.

Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

Python String Exercises: Get a string made of 4 copies of the last two characters of a specified string

Sample Solution:

Python Code:

# Define a function named insert_end that takes one argument, 'str'.
def insert_end(str):
    # Extract the last two characters from the input string 'str' and store them in 'sub_str'.
    sub_str = str[-2:]
    
    # Multiply 'sub_str' by 4 and return the result, effectively repeating the last two characters four times.
    return sub_str * 4

# Call the insert_end function with different input strings and print the results.
print(insert_end('Python'))    # Output: 'onononon'
print(insert_end('Exercises')) # Output: 'eseseses'

Sample Output:

onononon                                                                                                      
eseseses 

Flowchart:

Flowchart: Function to get a string made of 4 copies of the last two characters of a specified string

For more Practice: Solve these Related Problems:

  • Write a Python function to extract the last two characters of a string and repeat them 4 times using multiplication.
  • Write a Python program to check if a string's length is at least 2, then return 4 copies of its last two characters.
  • Write a Python program to implement this repetition using slicing and the * operator.
  • Write a Python function to recursively build a string consisting of 4 repeated copies of the last two characters.

Go to:


Previous: Write a Python function to insert a string in the middle of a string.
Next: Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.