Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python แสดงตัวอักษรที่อยู่ในสตริงทั้งสองแต่ไม่ซ้ำกัน


เมื่อต้องการแสดงตัวอักษรที่อยู่ในทั้งสองสตริงแยกกันแต่ไม่ซ้ำกัน ให้รับ input จากผู้ใช้ และใช้ 'list' และ 'set' เพื่อบรรลุเป้าหมาย

ลิสต์สามารถเก็บค่าที่หลากหลายได้ เมธอด 'list' แปลง iterable ให้เป็นชนิดลิสต์

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 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

คำอธิบาย

  • รับ input สองค่า: สตริงแรกและสตริงที่สอง
  • ดำเนินการ intersection บนสตริง
  • ทำหลังแปลงสตริงเป็นโครงสร้าง 'set'
  • ผลลัพธ์ของการดำเนินการนี้แปลงเป็นลิสต์และเก็บในตัวแปร
  • วนลูปและแสดงบนคอนโซล