Pythonで数字とアルファベットの数をカウントする方法は何ですか?
Pythonのisalpha()およびisdigit()メソッドを使用して、文字列内の数字と文字の数を数えることができます。以下はサンプルコードです:
def count_alpha_digit(s):
alpha_count = 0
digit_count = 0
for char in s:
if char.isalpha():
alpha_count += 1
elif char.isdigit():
digit_count += 1
return alpha_count, digit_count
s = "Hello123"
alpha_count, digit_count = count_alpha_digit(s)
print(f"字母个数:{alpha_count}")
print(f"数字个数:{digit_count}")
このコードを実行すると、以下の出力が得られます。
字母个数:5
数字个数:3