檢查字串是否包含任何特殊字元的程式


Python 幫助我們根據開發人員的需求和應用程式開發程式碼。它提供了多個模組、包、函式和類,使程式碼更有效率。

使用 Python 語言,我們可以檢查字串是否包含任何特殊字元。有幾種方法可以檢查字串中的特殊字元,讓我們一一來看。

使用正則表示式

Python 中的 re 模組提供了對正則表示式的支援,正則表示式是用於匹配字串中字元組合的模式。正則表示式模式 [^a−zA−Z0−9\s] 匹配字串中任何非字母數字字元(不包括空格)。re.search() 函式搜尋字串以匹配模式,如果找到匹配項則返回 Match 物件。

示例

在本例中,為了檢查字串中是否存在任何特殊字元,我們使用正則表示式。

import re
s = "Hello"
def has_special_char(s):
   pattern = r'[^a-zA-Z0-9\s]' 
   output = bool(re.search(pattern, s))
   if output == True:
      print(s, "has the special characters in it") 
   else:
      print(s, "has no special characters in it")
has_special_char(s)

輸出

Hello has no special characters in it

使用字串模組

Python 中的 string 模組提供包含字元集的常量,例如 string.punctuation,它包含所有 ASCII 標點符號字元。讓我們看一個例子 -

import string
s = "Hello Welcome to Tutorialspoint"
def has_special_char(s):
   output = any(c in string.punctuation for c in s)
   if output == True:
      print(s, "has the special characters in it") 
   else:
      print(s, "has no special characters in it")
has_special_char(s)

輸出

Hello Welcome to Tutorialspoint. has the special characters in it

更新於: 2023年11月6日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.