按字符数拆分字符串 [英] Split string by count of characters

查看:72
本文介绍了按字符数拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用字符串方法来做到这一点:

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

在我的文件中,我有类似 1.012345e0070.123414e-004-0.1234567891.21423 的内容...这意味着数字之间没有分隔符.

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

现在,如果我从这个文件中读取一行,我会得到一个类似上面的字符串,我想在例如之后拆分12 个字符.就我所见,使用 str.split() 或任何其他字符串方法无法做到这一点,但也许我忽略了一些东西?

Now if I read a line from this file I get a string like above which I want to split after e.g. 12 characters. There is no way to do this with something like str.split() or any other string method as far as I've seen but maybe I'm overlooking something?

谢谢

推荐答案

由于您想以不寻常的方式进行迭代,生成器是一种很好的抽象方法:

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

产生:

1.012345e007
0.123414e-00
4-0.12345678
91.21423

(看起来不对,但那些是 12 个字符的块)

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

这篇关于按字符数拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆