📜  Python – 提取 K 长度的子串

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

Python – 提取 K 长度的子串

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

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

# Python3 code to demonstrate working of
# Extract K length substrings
# Using list comprehension + string slicing
  
# initializing string 
test_str = "Geeks"
  
# printing original string 
print("The original string is : " + str(test_str))
  
# initializing K 
K = 3
  
# Extract K length substrings
# 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) if len(test_str[i:j]) == K]
  
# printing result 
print("All K length substrings of string are : " + str(res))
输出 :
The original string is : Geeks
All K length substrings of string are : ['Gee', 'eek', 'eks']

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

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