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

Python – ทดสอบสตริงในลิสต์ตัวอักษรและในทางกลับกัน

เมื่อต้องการทดสอบว่าสตริงอยู่ในลิสต์ตัวอักษร (รวมตัวอักษรซ้ำได้) และในทางกลับกัน สามารถใช้ตัวดำเนินการ in และ join() ได้

ตัวอย่าง

my_string = 'python'
print("The string is :")
print(my_string)
my_key = ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't']
print("The key is ")
print(my_key)
joined_list = ''.join(my_key)
my_result = my_string in joined_list
print("The result is :")
if my_result == True:
    print("The string is present in the character list")
else:
    print("The string is not present in the character list")

ผลลัพธ์

The string is : python
The key is ['p', 'y', 't', 'h', 'o', 'n', 't', 'e', 's', 't']
The result is : The string is present in the character list

คำอธิบาย

  • กำหนดสตริงเป้าหมายและลิสต์ตัวอักษร (มีตัวซ้ำเพียงพอสำหรับ 'python')

  • ใช้ ''.join(my_key) รวมลิสต์ตัวอักษรเป็นสตริงเดียว

  • ใช้ my_string in joined_list ตรวจสอบว่าเป็น substring หรือไม่

  • แสดงข้อความตามผลลัพธ์ Boolean