Python 程序检查字符串是否包含任何唯一字符
在本教程中,我们将编写一个程序来检查字符串是否包含任何特殊字符。它在 Python 中很简单。
我们在 string 模块中有一组特殊字符。我们可以用它来检查字符串是否包含任何特殊字符。让我们来看看编写程序的步骤。
导入 string 模块。
将 string.punctuation 中的特殊字符存储在变量中。
初始化一个字符串。
使用 map 函数检查字符串是否具有特殊字符。
打印结果,无论是否有效。
示例
# importing the string module
import string
# special characters
special_chars = string.punctuation
# initializing a string
string_1 = "Tutori@lspoinT!"
string_2 = "Tutorialspoint"
# checking the special chars in the string_1
bools = list(map(lambda char: char in special_chars, string_1))
print("Valid") if any(bools) else print("Invalid")
# checking the special chars in the string_2
bools = list(map(lambda char: char in special_chars, string_2))
print("Valid") if any(bools) else print("Invalid")输出
如果你运行上面的程序,你会得到以下结果。
Valid Invalid
结论
可以将代码移动到一个函数中,避免代码中的冗余。如果你对本教程有任何疑问,请在评论部分中提及。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP