python - 如何在 Python 中格式化九位数字的字符串?

标签 python string pandas string-formatting

我有一系列字符串,例如:"024764108""002231531""005231329",它们正好是 9 位数字.我想将 - 添加到每组 3 位数字。我想要的结果如下: “024-764-108”“002-231-531”“005-231-329”。 我如何向 python 解释我的想法?

最佳答案

这是一个动态的解决方案:

In [41]: df
Out[41]:
               num
0        024764108
1        002231531
2        005231329
3  012345678901234

In [42]: df.num.str.extractall(r'(\d{3})').groupby(level=0)[0].apply('-'.join)
Out[42]:
0            024-764-108
1            002-231-531
2            005-231-329
3    012-345-678-901-234
Name: 0, dtype: object

关于python - 如何在 Python 中格式化九位数字的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50282532/

相关文章:

python - 使用 SQLAlchemy 和 Flask jsonify 返回 JSON 格式的连接表

java - 将字符串 ("2022-12-23T07:20:00") 时间转换为 ZonedDateTime

Python:在 Pandas 中进行多列聚合

python - 仅更改 pandas DataFrame 中的数值数据

python - 如何在 Pandas 中复制行?

python - 为 "Four fours"谜题制作解谜器

python click 设置选项的允许值

javascript - javascript 中的预期标识符或字符串

python - 将空白字符串替换为 nan

python - 如何使用pymssql将数据帧写入mssql?