w3resource

Python: n (non-negative integer) copies of the first 2 characters of a given string

Python Basic: Exercise-23 with Solution

Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.

Pictorial Presentation:

n (non-negative integer) copies of the first 2 characters of a given string

Sample Solution:-

Python Code:

def substring_copy(str, n):
  flen = 2
  if flen > len(str):
    flen = len(str)
  substr = str[:flen]
  
  result = ""
  for i in range(n):
    result = result + substr
  return result
print(substring_copy('abcdef', 2))
print(substring_copy('p', 3));

Sample Output:

abab                                                                                                          
ppp

Flowchart:

Flowchart: n (non-negative integer) copies of the first 2 characters of a given string.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count the number 4 in a given list.
Next: Write a Python program to test whether a passed letter is a vowel or not.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")