检查字符串是否包含任何特殊字符的程序


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.