Python – N 個大小為 K 的帶有獨特字元的子字串


當需要拆分“N”大小的子字串和“K”個不同的字元時,對其進行迭代,並使用“集合”方法來獲取不同的組合。

示例

以下是演示

my_string = 'Pythonisfun'
print("The string is : ")
print(my_string)

my_substring = 2
my_chars = 2
my_result = []

for idx in range(0, len(my_string) - my_substring + 1):
   if (len(set(my_string[idx: idx + my_substring])) == my_chars):
      my_result.append(my_string[idx: idx + my_substring])
print("The resultant string is : ")
print(my_result)

輸出

The string is :
Pythonisfun
The resultant string is :
['Py', 'yt', 'th', 'ho', 'on', 'ni', 'is', 'sf', 'fu', 'un']

解釋

  • 定義一個字串並顯示在控制檯上。

  • 子字串和字元定義。

  • 定義一個空列表。

  • 與子字串中的數字相關的字串進行迭代。

  • 如果字串中唯一字元的長度等於字元,則將其附加到空列表中。

  • 這是顯示在控制檯上的結果。

更新於:20-9-2021

181 次瀏覽

職業生涯起步

完成課程獲取認證

開始
廣告
© . All rights reserved.