欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字符串按位数分割

程序员文章站 2022-06-11 17:14:34
# 以分割银行卡账号为例,每四位以空格分割def SplitString(numberstring, num=4, sign=' '): # 经常传入的数据转化为字符串 numstring = str(numberstring) # 获取传入的截取长度个符号,开始的下标与结束下标 num = num ......
# 以分割银行卡账号为例,每四位以空格分割
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