使用 Python 的字符串的子字符串 [英] Substrings of a string using Python

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

问题描述

你能用 abcd子字符串>?

How many substrings can you make out of a string like abcd?

我怎样才能得到它的所有子字符串:

How can I get all of its substrings:

['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

推荐答案

试试这个:

def consecutive_groups(iterable):
    s = tuple(iterable)
    for size in range(1, len(s)+1):
        for index in range(len(s)+1-size):
            yield iterable[index:index+size]

>>> print list(consecutive_groups('abcd'))
['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

而且组合数简单地等于1到字符串长度的和,相当于n * (n + 1)/2.

And the number of combinations is simply equal to the sum from 1 to the length of the string, which is equivalent to n * (n + 1) / 2.

顺便说一句,如果你想避免重复,你可以简单地在生成器函数中使用本地定义的集合,如下所示:

By the way, if you want to avoid duplicates, you can simply use a locally-defined set in the generator function, like so:

def consecutive_groups(iterable):
    s = tuple(iterable)
    seen = set()
    for size in range(1, len(s)+1):
        for index in range(len(s)+1-size):
            slc = iterable[index:index+size]
            if slc not in seen:
                seen.add(slc)
                yield slc

该代码有点笨拙,可能会针对缩进进行优化,但它可以用于概念验证.

That code is a little more unwieldy and could probably be optimized for indentation, but it will do for a proof of concept.

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

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