python - 如果可能的话,在字符串的每 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
解决方案
这将在没有正则表达式的情况下解决您的问题:
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 "--->"
推荐阅读
- excel - 枢轴将过滤后的值合并为一个并按颜色分隔
- docker - Docker compose 不构建,而 docker build 没有任何问题
- paypal - 如何收集付款信息并在以后收取不同的金额
- c# - 在 REST API 中启动独立进程
- amazon-web-services - 带有 jenkins 和 appsec.yml 的 AWS Codebuild 和 codedeploy 环境
- airflow - 在 pipenv 安装的 Centos 7 上找不到气流.cfg
- android - Buildozer 类未找到 b'org/renpy/android/PythonActivity'
- android - 我还可以对我的应用应用哪些安全措施?
- mysql - 用逗号分隔输入和搜索的 SQL 存储过程
- pytorch - 使用 MS-COCO 格式作为 PyTorch MASKRCNN 的输入