检查字符串是否包含任何唯一字符的Python程序

在本教程中,我们将编写一个程序来检查字符串是否包含任何特殊字符。在Python中很简单。

字符串模块中将有一组特殊字符。我们可以用那个来检查一个字符串是否包含任何特殊字符。让我们看看编写程序的步骤。

  • 导入字符串模块。

  • 将来自string.punctuation的特殊字符存储在变量中。

  • 初始化字符串。

  • 使用映射功能检查字符串是否具有特殊字符。

  • 打印结果,无论是否有效。

示例

# 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

结论

您可以将代码移至某个函数,以避免代码中的冗余。如果您对本教程有任何疑问,请在评论部分中提及。