在Python中,统计字符串中数字的个数可以通过以下几种方法实现:
1. 使用`isdigit()`函数:
def count_digits(s):
count = 0
for char in s:
if char.isdigit():
count += 1
return count
s = 'abc123xyz456'
print(count_digits(s)) 输出:6
2. 使用`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
3. 使用`Counter`类(来自`collections`模块):
from collections import Counter
def count_digits_with_counter(s):
return Counter(s).get('0', 0) + Counter(s).get('1', 0) + Counter(s).get('2', 0) + Counter(s).get('3', 0) + Counter(s).get('4', 0) + Counter(s).get('5', 0) + Counter(s).get('6', 0) + Counter(s).get('7', 0) + Counter(s).get('8', 0) + Counter(s).get('9', 0)
s = 'abc123xyz456'
print(count_digits_with_counter(s)) 输出:6
4. 使用`dict.setdefault()`方法:
def count_digits_with_setdefault(s):
count_dict = {}
for char in s:
if char.isdigit():
count_dict.setdefault(char, 0)
count_dict[char] += 1
return count_dict
s = 'abc123xyz456'
print(count_digits_with_setdefault(s)) 输出:{1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}
5. 使用`defaultdict`:
from collections import defaultdict
def count_digits_with_defaultdict(s):
count_dict = defaultdict(int)
for char in s:
if char.isdigit():
count_dict[char] += 1
return count_dict
s = 'abc123xyz456'
print(count_digits_with_defaultdict(s)) 输出:defaultdict(
, {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})
6. 使用`len()`函数:
def count_digits_with_len(s):
return len(s.replace(' ', '')) 假设字符串中不包含空格
s = 'abc123xyz456'
print(count_digits_with_len(s)) 输出:6
以上方法均可用于统计字符串中数字的个数。您可以根据具体需求选择合适的方法