Python 每日一练 => 等分字符串
import re
# 'F0-B4-29-98-CE-34'
'-'.join(re.findall(r'.{2}', 'F0B42998CE34'))
使用场景:字符串平均切割、MAC 地址切割等操作。
1
krixaar 2022-08-12 11:39:28 +08:00 13
from textwrap import wrap
# 'F0-B4-29-98-CE-34' '-'.join(wrap('F0B42998CE34', 2)) |
3
wang9571 2022-08-12 11:50:59 +08:00 2
'-'.join(s[x:x+2] for x in range(0, len(s), 2))
|
5
piglei 2022-08-12 19:25:09 +08:00
好答案前面有了,我再多贡献一条基于正则的花活。若干年前学自《精通正则表达式》,对于当时的我过于震撼,牢记至今:
>>> s = 'F0B42998CE34' >>> import re >>> re.sub(r'(?<=.)(?=(..)+$)', '-', s) 'F0-B4-29-98-CE-34' |
6
l4ever 2022-08-13 19:22:35 +08:00
string='20220202'
# out put-> 2022-02-02 楼下的请解答 |
7
elboble 2022-08-13 22:50:18 +08:00
''.join([(str[i]+('-' if i%2 and not (i==1 or i == len(str)-1) else '')) for i in range(len(str))])
|
8
brucmao 2022-08-19 16:23:18 +08:00
```python
s = 'F0B42998CE34' def chunk(iterable, chunk_size, on_chunk=None): on_chunk = on_chunk or (lambda x:x) return [on_chunk(chunk) for chunk in zip(*[iter(iterable)] * chunk_size)] res = chunk(s,2,''.join) print('-'.join(res)) ``` https://github.com/lisonge/lisonge.gitHub.io/raw/main/1x1.png#YGBgcHl0aG9uCgpzID0gJ0YwQjQyOTk4Q0UzNCcKCmRlZiBjaHVuayhpdGVyYWJsZSwgY2h1bmtfc2l6ZSwgb25fY2h1bms9Tm9uZSk6CiAgICBvbl9jaHVuayA9IG9uX2NodW5rIG9yIChsYW1iZGEgeDp4KQogICAgcmV0dXJuIFtvbl9jaHVuayhjaHVuaykgZm9yIGNodW5rIGluIHppcCgqW2l0ZXIoaXRlcmFibGUpXSAqIGNodW5rX3NpemUpXQoKcmVzID0gY2h1bmsocywyLCcnLmpvaW4pCnByaW50KCctJy5qb2luKHJlcykpCgoKCmBgYA== |