简体   繁体   English

生成给定字符串的所有子字符串

[英]Generate all substrings of a given string

I want to generate all the possible substrings from a given string without redundant values as follows:我想从给定的字符串中生成所有可能的子字符串而没有冗余值,如下所示:

input: 'abba'输入: 'abba'

output: 'a','b','ab','ba','abb','bba'输出: 'a','b','ab','ba','abb','bba'

Here is my code这是我的代码

s='abba' 
for i in range (0,len(s)):
    for j in range (i+1,len(s)):
        print(s[i:j])

My output is 'a','ab','abb','b','bb','b'我的输出是'a','ab','abb','b','bb','b'

As you can see from the output 'b' is repeated, and 'bba' does not exist.正如您从输出中看到的那样, 'b'是重复的,而'bba'不存在。

I want to know and learn the right logic to produce all unique substrings.我想知道并学习生成所有唯一子字符串的正确逻辑。

Fixing the indexing a bit稍微修复索引

s='abba' 
for i in range (0,len(s)):
    for j in range (i,len(s)):
        print(s[i:(j+1)])

yields the following output产生以下输出

a
ab
abb
abba
b
bb
bba
b
ba
a

Basically, the indexing fix takes into account that基本上,索引修复考虑到

  • 'abba'[3:3] produces just zero-length string '' 'abba'[3:3]只产生零长度的字符串''

but

  • 'abba'[3:4] produces string 'a' which has length one. 'abba'[3:4]产生长度为 1 的字符串'a'

Duplicates you may remove by using set() , as follows:您可以使用set()删除重复项,如下所示:

s='abba'
ss = set()
for i in range (0,len(s)):
    for j in range (i,len(s)):
        ss.add(s[i:(j+1)])
        
print(sorted(ss))

Then you will have the following result ['a', 'ab', 'abb', 'abba', 'b', 'ba', 'bb', 'bba'] .然后你会得到以下结果['a', 'ab', 'abb', 'abba', 'b', 'ba', 'bb', 'bba']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按字母顺序生成给定字符串的所有子字符串(按字典顺序) - Generate all substrings(in lexicographic order)of given string in alphabetical order 在python中递归查找给定字符串的所有子字符串 - Find all substrings of a given string recursively in python 有效地生成字符串的所有可能子串的列表 - Efficiently generate a list of all possible substrings of a string 是否有更好的方法来查找出现在给定字典中的字符串的所有连续子字符串 - Is there a better way to find all the contiguous substrings of a string that appear in a given dictionary 使用 python 删除字符串中包含任何给定子字符串的所有单词 - Remove all words in a string that contain any given substrings using python 查找给定字符串的所有后续子字符串的最有效方法是什么? - Which is the most efficient method for finding all subsequent substrings of a given string? 按顺序生成所有可能的子串 - Generate all possible substrings in sequence 程序提供给定字符串中所有潜在子字符串的列表,需要过滤掉不按字母顺序排列的子字符串 - Program gives list of all potential substings from a given string, need to filter out substrings not in alphabetical order 给定一个字符串如何在python中找到所有非空白子字符串的开始和结束索引 - Given a string how to find start and end index of all non-whitespace substrings in python 查找字符串的所有“分散子串” - Find all “scattered substrings” of a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM