Split string into strings by length?

后端 未结 15 2086
半阙折子戏
半阙折子戏 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 06:50
    def split2len(s, n):
        def _f(s, n):
            while s:
                yield s[:n]
                s = s[n:]
        return list(_f(s, n))
    
    0 讨论(0)
  • 2020-11-27 06:51
    # spliting a string by the length of the string
    
    def len_split(string,sub_string):
        n,sub,str1=list(string),len(sub_string),')/^0*/-'
        for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
            n.insert(i,str1)   
        n="".join(n)
        n=n.split(str1)
        return n
    
    x="divyansh_looking_for_intership_actively_contact_Me_here"
    sub="four"
    print(len_split(x,sub))
    
    # Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']
    
    0 讨论(0)
  • 2020-11-27 06:52

    Here is a one-liner that doesn't need to know the length of the string beforehand:

    from functools import partial
    from StringIO import StringIO
    
    [l for l in iter(partial(StringIO(data).read, 4), '')]
    

    If you have a file or socket, then you don't need the StringIO wrapper:

    [l for l in iter(partial(file_like_object.read, 4), '')]
    
    0 讨论(0)
  • 2020-11-27 06:57
    >>> x = "qwertyui"
    >>> chunks, chunk_size = len(x), len(x)/4
    >>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
    ['qw', 'er', 'ty', 'ui']
    
    0 讨论(0)
  • 2020-11-27 06:58

    I tried Alexanders answer but got this error in Python3:

    TypeError: 'float' object cannot be interpreted as an integer

    This is because the division operator in Python3 is returning a float. This works for me:

    >>> x = "qwertyui"
    >>> chunks, chunk_size = len(x), len(x)//4
    >>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
    ['qw', 'er', 'ty', 'ui']
    

    Notice the // at the end of line 2, to ensure truncation to an integer.

    0 讨论(0)
  • 2020-11-27 06:59
    length = 4
    string = "abcdefgh"
    str_dict = [ o for o in string ]
    parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ]   ) for j in xrange(len(string)/length  )]
    
    0 讨论(0)
提交回复
热议问题