首页 > 解决方案 > 如果可能的话,在字符串的每 3 位加上连字符,在最后一组加上 2 位

问题描述

我需要创建一个允许字符串用户输入的程序。我只需要选择数字,然后将它们按 3 位数分组。如果字符串的长度不能被 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

标签: python

解决方案


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

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

推荐阅读