Python Split string in a certain length

前端 未结 1 1190
礼貌的吻别
礼貌的吻别 2021-01-18 23:07

I have this situation: I got a string that I want to split every X characters. My problem is that the split method only splits the string based on a string such as:

相关标签:
1条回答
  • 2021-01-18 23:52

    This is called slicing:

    >>> paragraph[:5], paragraph[5:]
    ('my pa', 'ragraph')
    

    To answer the "split every X characters" question, you would need a loop:

    >>> x = 5
    >>> [paragraph[i: i + x] for i in range(0, len(paragraph), x)]
    ['my pa', 'ragra', 'ph']
    

    There are more solutions to this though, see:

    • Split python string every nth character?
    • What is the most "pythonic" way to iterate over a list in chunks?
    0 讨论(0)
提交回复
热议问题