Split string by count of characters

前端 未结 8 2396
青春惊慌失措
青春惊慌失措 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:00

    Since you want to iterate in an unusual way, a generator is a good way to abstract that:

    def chunks(s, n):
        """Produce `n`-character chunks from `s`."""
        for start in range(0, len(s), n):
            yield s[start:start+n]
    
    nums = "1.012345e0070.123414e-004-0.1234567891.21423"
    for chunk in chunks(nums, 12):
        print chunk
    

    produces:

    1.012345e007
    0.123414e-00
    4-0.12345678
    91.21423
    

    (which doesn't look right, but those are the 12-char chunks)

提交回复
热议问题