เมื่อต้องการแสดงตัวอักษรที่อยู่ในสตริงแรกแต่ไม่ใช่สตริงที่สอง ให้รับ input สองสตริงจากผู้ใช้ ใช้ 'set' หาความต่างระหว่างสองสตริง
Python มีชนิดข้อมูล 'set' ซึ่งมีองค์ประกอบที่ไม่ซ้ำกันเท่านั้น
Set มีประโยชน์ในการดำเนินการ intersection, difference, union และ symmetric difference
ตัวอย่าง
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
คำอธิบาย
- รับ input สองสตริงจากผู้ใช้
- แปลงเป็น set และคำนวณความต่าง
- แปลงความต่างนี้เป็นลิสต์
- กำหนดค่าให้ตัวแปร
- วนลูปและแสดงบนคอนโซล