如果可能的话,在字符串的每3位加上连字符,在最后一组加上2位

2024-09-30 12:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个程序,允许用户输入字符串。我只需要选择数字,然后按每个数字3个数字分组。如果字符串的长度不能被3整除,那么在最后一组有两个数字。有人能帮我吗

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

Tags: sample字符串用户程序targetinputoutput数字
1条回答
网友
1楼 · 发布于 2024-09-30 12:33:18

这将在没有regex的情况下解决您的问题:

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

相关问题 更多 >

    热门问题