python - 将 Python 中的字符串拆分为长度恒定但右对齐的 block

标签 python string slice

基本上,我有一个像“12345678”这样的字符串,需要一个包含此信息的列表,但要分成长度为 3 的子字符串。问题是,我需要它右对齐,所以输出必须是 ['12', '345', '678'] 而不是 ['123', '456', '78']
我如何用很少的代码行最好地实现,并且最好不使用额外的导入?

最佳答案

很容易改编 How do I split a list into equally-sized chunks? 的最佳答案:

def chunks_rightaligned(l, n):
    orphan = len(l) % n
    if orphan:
        yield l[: orphan]         
    for i in range(orphan, len(l), n):
        yield l[i : i + n]

这首先产生剩余长度的 block ,然后从孤立大小而不是 0 开始以 block 大小的步长迭代索引。

演示:

>>> def chunks_rightaligned(l, n):
...     orphan = len(l) % n
...     if orphan:
...         yield l[: orphan]         
...     for i in range(orphan, len(l), n):
...         yield l[i : i + n]
... 
>>> list(chunks_rightaligned("12345678", 3))
['12', '345', '678']
>>> list(chunks_rightaligned("1234567", 3))
['1', '234', '567']
>>> list(chunks_rightaligned("123456", 3))
['123', '456']

关于python - 将 Python 中的字符串拆分为长度恒定但右对齐的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896431/

相关文章:

python - 从python中的数组制作数组

python - 输出 HTML 无序列表 python

Python,生成随机的括号字符串

python - 创建一个函数,该函数接受以字符串形式给出的方程并计算它

tensorflow 通过(不同范围的 2d)切片列表更改/分配矩阵元素值

python - 使用 ElementTree 解析带有特殊字符的 XML

Python lxml : Ignore XML declaration (errors)

python - 将列表字典转换为元组字典

java - 如何计算字符串中特定字符的数量?

java - 使用 Java 扫描文件并根据其内容过滤它们(反向切片)