📌  相关文章
📜  测试字符串是否只有数字和字母的Python程序

📅  最后修改于: 2022-05-13 01:55:08.441000             🧑  作者: Mango

测试字符串是否只有数字和字母的Python程序

给定一个字符串,我们的任务是编写一个Python程序来检查字符串是否包含数字和字母,而不是标点符号。

例子:

Input : test_str = 'Geeks4Geeks'
Output : True
Explanation : Contains both number and alphabets.

Input : test_str = 'GeeksforGeeks'
Output : False
Explanation : Doesn't contain number.

方法#1:使用isalpha() + isdigit() + any() + all() + isalnum()

在此,我们使用 all()、isalpha() 和 isdigit() 检查所有包含字母和数字组合的数字。 any() 和 isalnum() 用于过滤掉标点符号的可能性。

Python3
# Python3 code to demonstrate working of
# Test if string contains both Numbers and Alphabets only
# Using isalpha() + isdigit() + any() + all() + isalnum()
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# conditional combination for getting result.
res = not ((all(idx.isdigit() for idx in test_str) or (all(idx.isalpha() 
            for idx in test_str)) or (any(not idx.isalnum() for idx in test_str))))
  
# printing result
print("Does string contain both numbers and alphabets only? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test if string contains both Numbers and Alphabets only
# Using regex
import re
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# conditional combination for getting result.
res = bool(re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A530"))
          
# printing result
print("Does string contain both numbers and alphabets only? : " + str(res))


输出:

The original string is : Geeks4Geeks
Does string contain both numbers and alphabets only? : True

方法#2:使用正则表达式

使用正则表达式是解决此问题的方法之一。

蟒蛇3

# Python3 code to demonstrate working of
# Test if string contains both Numbers and Alphabets only
# Using regex
import re
  
# initializing string
test_str = 'Geeks4Geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# conditional combination for getting result.
res = bool(re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A530"))
          
# printing result
print("Does string contain both numbers and alphabets only? : " + str(res))

输出:

The original string is : Geeks4Geeks
Does string contain both numbers and alphabets only? : True