如果可能,在字符串的每 3 位数字中放置连字符,在最后一组中添加 2 位数字



我需要创建一个允许字符串用户输入的程序。我只需要选择数字,然后按每个数字对它们进行分组。如果字符串的长度不能被 3 整除,则在最后一组有 2 位数字。谁能帮我?

sample user input : ue3j8dj2pud7y3g378
Target output: 382-733-78
sample user input : babdh3uh23737gvrh27h3h4
Target output: 323-737-27-34
Sample user input: bs34bhev26gv362
Target output: 342-63-62

这将在没有正则表达式的情况下解决您的问题:

my_string= 'ue3j8dj2pud7y3g378'
x = ''.join(c for c in my_string if c.isdigit())
y=""
myInt = len(x)- 5
rem = myInt % 3
quo = myInt/3
if rem == 0 and quo==1:

y= '-'.join([x[:3], x[3:6], x[6:]])
print y
elif rem == 2 and quo ==1:
y ='-'.join([x[:3], x[3:6], x[6:8],x[8:]])
print y
elif rem == 2 and quo == 0:
y ='-'.join([x[:3], x[3:5], x[5:]])
print y
else:
print "--->"

最新更新