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

หาตัวอักษรร่วมระหว่างสอง String ใน Python

บทนำ

การหาตัวอักษรที่ปรากฏในทั้งสองสตริง (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ชื่อตัวอย่างผลลัพธ์
&Intersectionset('hey') & set('jane'){'e'}
|Unionset('hey') | set('jane'){'h','e','y','j','a','n'}
-Differenceset('hey') - set('jane'){'h','y'}
^Symmetric Diffset('hey') ^ set('jane'){'h','y','j','a','n'}