Split string by count of characters

前端 未结 8 2383
青春惊慌失措
青春惊慌失措 2020-11-30 07:45

I can\'t figure out how to do this with string methods:

In my file I have something like 1.012345e0070.123414e-004-0.1234567891.21423... which means there is no deli

相关标签:
8条回答
  • 2020-11-30 08:12

    I always thought, since string addition operation is possible by a simple logic, may be division should be like this. When divided by a number, it should split by that length. So may be this is what you are looking for.

    class MyString:
        def __init__(self, string):
            self.string = string
        def __div__(self, div):
            l = []
            for i in range(0, len(self.string), div):
                l.append(self.string[i:i+div])
            return l
    
    >>> m = MyString(s)
    >>> m/3
    ['abc', 'bdb', 'fbf', 'bfb']
    
    
    >>> m = MyString('abcd')
    >>> m/3
    ['abc', 'd']
    

    If you don't want to create an entirely new class, simply use this function that re-wraps the core of the above code,

    >>> def string_divide(string, div):
           l = []
           for i in range(0, len(string), div):
               l.append(string[i:i+div])
           return l
    
    >>> string_divide('abcdefghijklmnopqrstuvwxyz', 15)
    ['abcdefghijklmno', 'pqrstuvwxyz']
    
    0 讨论(0)
  • 2020-11-30 08:20
    from itertools import izip_longest
    
    def grouper(n, iterable, padvalue=None):
        return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
    
    0 讨论(0)
提交回复
热议问题