1. 使用内置函数 `isdigit()`:
string = '1234'
is_digit = string.isdigit()
print(is_digit) 输出:True
2. 使用 `int()` 函数结合 `for` 循环:
string = '1234'
for char in string:
try:
int(char)
print(f'{char} 是数字字符')
except ValueError:
print(f'{char} 不是数字字符')
3. 使用 `isnumeric()` 方法(Python 3.6+):
string = '1234'
is_numeric = string.isnumeric()
print(is_numeric) 输出:True
4. 使用正则表达式:
import re
string = '1234'
if re.match(r'^[0-9]+$', string):
print('是数字字符')
else:
print('不是数字字符')
5. 自定义函数 `is_number()` 来判断是否为数字,包括整数、浮点数和Unicode数字:
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
print(is_number('1234')) 输出:True
print(is_number('1.3')) 输出:True
print(is_number('-1.37')) 输出:True
print(is_number('1e3')) 输出:True
print(is_number('5')) 输出:False
print(is_number('2')) 输出:False
print(is_number('四')) 输出:False
以上方法可以帮助你分辨字符串中的字符是否为数字。