字符串按位數分割

# 以分割銀行卡帳號爲例,每四位以空格分割def SplitString(numberstring, num=4, sign=' '):    # 常常傳入的數據轉化爲字符串    numstring = str(numberstring)    # 獲取傳入的截取長度個符號,開始的下標與結束下標    num = num    sign = sign    start_index = 0    end_index = num    str_list =[]    # 須要遍歷的次數    len_str=int(len(numstring))    for i in range(int(len_str/num+1)):        str_list.append(numstring[start_index:end_index])        str_list.append(sign)        start_index = end_index        end_index += num    outstr = "".join(str_list)    len_outstr = len(outstr)    if len_str % num == 0:        last_outstr = outstr[0:len_outstr-2]    else:        last_outstr = outstr[0:len_outstr-1]    return last_outstr
相關文章
相關標籤/搜索