2018年1月8日 星期一

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

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.
Sample Solution:-
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('avbcdef', 4))
print(substring_copy('ap', 3));
print(substring_copy('p', 5));

============ RESTART: F:/Python_APSC/py-ex-basic-23.py ============
avavavav
apapap
ppppp
>>> 

沒有留言:

張貼留言

2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2

 2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2 AngularJS 實例 <!DOCTYPE html> <html> <head> &...