Python 文字列が英数字か判定する方法【isalpha/isalnum】
isalpha()メソッドとisdigit()メソッドを使用して、文字列がすべて文字または数字であるかどうかを判断することができます。以下はサンプルコードです:
def is_alpha_or_digit(s):
return s.isalpha() or s.isdigit()
# 测试
print(is_alpha_or_digit("hello123")) # False
print(is_alpha_or_digit("hello")) # True
print(is_alpha_or_digit("123")) # True
上記の例では、is_alpha_or_digit()関数は、文字列を引数として受け取り、isalpha()メソッドとisdigit()メソッドを使用して、その文字列がすべて文字または数字であるかどうかを判断します。文字列がすべて文字または数字であればTrueを返し、そうでなければFalseを返します。