📜  Python|获取给定字符串的所有子字符串

📅  最后修改于: 2022-05-13 01:55:10.753000             🧑  作者: Mango

Python|获取给定字符串的所有子字符串

有很多问题需要我们获取一个字符串的所有子字符串。这个特殊的实用程序在竞争性编程中非常流行,并且使用速记来解决这个问题总是很方便。让我们讨论一些可以解决这个问题的方法。

方法#1:使用列表理解+字符串切片
列表理解和字符串切片的组合可用于执行此特定任务。这只是执行此任务的蛮力方法。

# Python3 code to demonstrate working of
# Get all substrings of string
# Using list comprehension + string slicing
  
# initializing string 
test_str = "Geeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Get all substrings of string
# Using list comprehension + string slicing
res = [test_str[i: j] for i in range(len(test_str))
          for j in range(i + 1, len(test_str) + 1)]
  
# printing result 
print("All substrings of string are : " + str(res))
输出 :

方法 #2:使用itertools.combinations()
也可以使用组合的内置函数来执行此特定任务,这有助于获取所有可能的组合,即来自 string 的子字符串。

# Python3 code to demonstrate working of
# Get all substrings of string
# Using itertools.combinations()
from itertools import combinations
  
# initializing string 
test_str = "Geeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# Get all substrings of string
# Using itertools.combinations()
res = [test_str[x:y] for x, y in combinations(
            range(len(test_str) + 1), r = 2)]
  
# printing result 
print("All substrings of string are : " + str(res))
输出 :