บทนำ
การหาตัวอักษรที่ปรากฏในทั้งสองสตริง (union ของ character sets) สามารถทำได้โดยแปลงเป็น set แล้วใช้ตัวดำเนินการ | (union)
ตัวอย่างโค้ด
str1 = 'hey'
str2 = 'jane'
print("String 1:", str1)
print("String 2:", str2)
# หาตัวอักษรร่วม (union)
chars = set(str1) | set(str2)
print("ตัวอักษรทั้งหมดที่ปรากฏ:")
for c in sorted(chars):
print(f" '{c}'")
ผลลัพธ์
String 1: hey String 2: jane ตัวอักษรทั้งหมดที่ปรากฏ: 'a' 'e' 'h' 'j' 'n' 'y'
คำอธิบาย
set(str1)→ {'h', 'e', 'y'}set(str2)→ {'j', 'a', 'n', 'e'}|(union) → {'h', 'e', 'y', 'j', 'a', 'n'}sorted()เรียงตามลำดับอักษร
Set Operations อื่นๆ สำหรับ String
| Operator | ชื่อ | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|---|
& | Intersection | set('hey') & set('jane') | {'e'} |
| | Union | set('hey') | set('jane') | {'h','e','y','j','a','n'} |
- | Difference | set('hey') - set('jane') | {'h','y'} |
^ | Symmetric Diff | set('hey') ^ set('jane') | {'h','y','j','a','n'} |