python - 在Python中查找字符串中的所有子字符串,我怎样才能做得更好?

标签 python python-3.x string algorithm substring

我怎样才能让它变得更好?有没有什么算法/方法可以让它更好、更短?

def sub_string_finder(string):
    given_string = string.upper()
    substring_of = []
    length = len(given_string)
    # find all substring and put it in substring array
    for i in range(length):
        for j in range(i + 1, length + 1):
            substring_of.append(given_string[i:j])
    return substring_of


s = input("Enter a string: ")
print(f"Number of substring: {len(sub_string_finder(s))}")
print(sub_string_finder(s))

“开发人员”的输出:

Number of substring: 45
['D', 'DE', 'DEV', 'DEVE', 'DEVEL', 'DEVELO', 'DEVELOP', 'DEVELOPE', 'DEVELOPER', 'E', 'EV', 'EVE', 'EVEL', 'EVELO', 'EVELOP', 'EVELOPE', 'EVELOPER', 'V', 'VE', 'VEL', 'VELO', 'VELOP', 'VELOPE', 'VELOPER', 'E', 'EL', 'ELO', 'ELOP', 'ELOPE', 'ELOPER', 'L', 'LO', 'LOP', 'LOPE', 'LOPER', 'O', 'OP', 'OPE', 'OPER', 'P', 'PE', 'PER', 'E', 'ER', 'R']

更新

这是迄今为止使用itertools组合得到的最终答案,感谢受访者。为了增加可读性,我们可以使用换行符。请记住Python allows line breaks在方括号和大括号之间。

from itertools import combinations


def sub_string_finder(string):
    substring_of = [
    string.upper()[i:j] 
    for i, j in combinations(range(len(string) + 1), r=2)
]
    return substring_of

如果您有兴趣了解Python列表推导式,可以查看this .

最佳答案

您可以将嵌套循环编写为一行。如果您从 i + 1 开始第二个内部,您也可以跳过检查 != ""

def sub_string_finder(string):
    given_string = string.upper()
    length = len(given_string)
    substring_of = [given_string[i:j] for i in range(length) for j in range(i + 1, length + 1)]

    return substring_of

或者使用来自itertools组合

substring_of = [given_string[i:j] for i, j in combinations(range(len(given_string) + 1), r=2) if given_string[i:j] != ""]

关于python - 在Python中查找字符串中的所有子字符串,我怎样才能做得更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59342573/

相关文章:

string - 有与 PadLeft/PadRight 等效的方法吗?

python - "name ' win32api ' is not defined"- 错误但包存在?

Python 3 UnicodeDecodeError - 如何调试 UnicodeDecodeError?

python - SQL语句错误中未使用所有参数

Python - 如何提取多个标签之间的元素

c++ - 该代码应该返回不带空格的字符串,但它返回字符串直到第一个空格字符

python - Kivy Widget id 在 __init__ 中访问

Python 窗口 : correct virtualenv paths

Python Click 命令无法识别选项

string - 字符串 2 的字谜是字符串 1 的子字符串