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
>>> 

沒有留言:

張貼留言

RFID TI 培訓影片系列

RFID TI 培訓影片系列  https://www.ti.com/zh-tw/video/series/rfid.html 培訓影片系列 RFID 隨著創新技術日益發展,RFID 和 RF 術語越來越容易讓人混淆。本訓練系列詳細介紹了使用案例、權衡技術優缺點,讓您清楚知道該選...