Python 字符串分组:每4个字符为一组
使用 Python 的字符串切片功能可以轻松实现将字符串每 4 个字符为一组进行分组。以下示例代码展示了如何实现这一功能:
def group_by_4_chars(string):
groups = []
for i in range(0, len(string), 4):
group = string[i:i+4]
groups.append(group)
return groups
# 示例用法
text = 'Python is a great language.'
groups = group_by_4_chars(text)
for group in groups:
print(group)
输出结果为:
Pyth
on i
s a
grea
t la
gua
ge.
在这个示例中,group_by_4_chars 函数将输入的字符串按照每 4 个字符分组,并返回一个包含所有分组的列表。然后,我们遍历这个列表并输出每个分组。
原文地址: https://www.cveoy.top/t/topic/pKG1 著作权归作者所有。请勿转载和采集!