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

沒有留言:

張貼留言

Node-Red --> MQTT --> Fuxa 開源碼網頁式圖控平台

Node-Red --> MQTT --> Fuxa      FUXA(一個開源的 Web HMI / SCADA 自動化監控軟體)的專案設定檔 。 這份設定檔完整定義了 HMI 監控畫面的 後端通訊(MQTT 連線、點位標籤) 與 前端網頁圖形介面(SVG 畫布...