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

Python - ตรวจสอบว่าสตริงมี Special Character หรือไม่

ใช้ re.compile() กับ Pattern ของ Special Characters ที่กำหนด แล้ว search() หาในสตริง

ตัวอย่างโค้ด

import re

def check_string(my_string):
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
    if regex.search(my_string) == None:
        print("String does not contain any special character.")
    else:
        print("String contains special characters.")

my_string = "PythonInterpreter"
print("The string is :")
print(my_string)
check_string(my_string)

ผลลัพธ์

The string is : PythonInterpreter
String does not contain any special character.

คำอธิบาย

  • Pattern [@_!#$%^&*()<>?/\|}{~:] รวมสัญลักษณ์พิเศษทั่วไป
  • regex.search(my_string) == None หมายถึงไม่พบ -> ไม่มี Special Char
  • โค้ดตัวอย่างมี Logic ผิด: พิมพ์ "contains" เมื่อเป็น None (ควรสลับกัน)
  • ผลลัพธ์จริงของ "PythonInterpreter" คือไม่มี Special Char