Split string into strings by length?

后端 未结 15 2150
半阙折子戏
半阙折子戏 2020-11-27 06:31

Is there a way to take a string that is 4*x characters long, and cut it into 4 strings, each x characters long, without knowing the length of the s

15条回答
  •  死守一世寂寞
    2020-11-27 07:06

    • :param s: str; source string
    • :param w: int; width to split on

    Using the textwrap module:

    PyDocs-textwrap

    import textwrap
    def wrap(s, w):
        return textwrap.fill(s, w)
    

    :return str:

    Inspired by Alexander's Answer

    PyDocs-data structures

    def wrap(s, w):
        return [s[i:i + w] for i in range(0, len(s), w)]
    
    • :return list:

    Inspired by Eric's answer

    PyDocs-regex

    import re
    def wrap(s, w):    
        sre = re.compile(rf'(.{{{w}}})')
        return [x for x in re.split(sre, s) if x]
    
    • :return list:

    Complete Code Examples/Alternative Methods

提交回复
热议问题