顯示兩個字串中存在的但不在兩者都存在的字母的 Python 程式
當需要分別顯示出現在兩個字串中但沒有重複的字母時,會獲取使用者輸入,並使用“列表”和“集合”來實現相同的功能。
列表可用於儲存異構值(即任何資料型別的資料,例如整數、浮點數、字串等)。“list”方法將給定的可迭代物件轉換為列表型別。
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 strings but not in both the strings are :")
for i in my_result:
print(i)輸出
Enter the first string...Jane Enter the second string...Kane The letters in strings but not in both the strings are : K J
解釋
- 獲取兩個使用者輸入 - 第一個字串和第二個字串。
- 對字串執行交集運算。
- 這是在將字串轉換為“集合”結構後完成的。
- 此操作的結果被轉換為列表並存儲在一個變數中。
- 對其進行迭代並在控制檯上顯示。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP