顯示第一個字串中但第二個字串中沒有的字母的Python程式


當需要顯示存在於第一個字串中但不存在於第二個字串中的字母時,需要從使用者處獲取兩個字串輸入。“集合”用於查詢兩個字串之間的差異。

Python帶有一種稱為“集合”的資料型別。此“集合”僅包含唯一元素。

集合可用於執行交集、差集、並集和對稱差集等運算。

示例

以下是相同的演示 -

 線上演示

my_str_1 = input("Enter the first string...")
my_str_2 = input("Enter the second string...")
my_result = list(set(my_str_1)-set(my_str_2))
print("The letters in first string but not in second string :")
for i in my_result:
   print(i)

輸出

Enter the first string...Jane
Enter the second string...Wane
The letters in first string but not in second string :
J

解釋

  • 從使用者處獲取兩個字串作為輸入。
  • 將它們轉換為集合,並計算它們的差集。
  • 將此差集轉換為列表。
  • 此值被賦值給一個變數。
  • 對它進行迭代,並在控制檯中顯示。

更新於:2021年3月12日

387 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.