首页 > 解决方案 > 将字符串更改为五个 python 的块

问题描述

如何更改字符串,以便每 5 个字符之间有一个空格?但是,我不希望在开头或结尾留出空间。

例如

"Yohomeyoverstack" will be "Yohom eyove rstac k"

"two"  will be "two"

标签: pythonpython-3.x

解决方案


使用slicing

前任:

s = "Yohomeyoverstack"
print( " ".join([s[i:i+5] for i in range(0, len(s), 5)]) )

输出:

Yohom eyove rstac k

推荐阅读