如何检测一个字符串是否为数字

'''
如何检测字符串是否位数字、数字和字母混合形式
'''
#检测字符串是否由字母或数字组成 isalnum
'''
Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string
'''
a = '123'
print(a.isalnum())#True

b = 'shaw'
print(b.isalnum())#True

c = 'shaw123'
print(c.isalnum())#True

d = 'th 123'
print(d.isalnum())#False

#检测字符串是否只由字母组成 isalpha
'''
Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string
'''
a = '123'
print(a.isalpha())#False

b = '123shaw'
print(b.isalpha())#False

c = 'shaw'
print(c.isalpha())#True

d = 'sha w'
print(d.isalpha())#False

#检测字符串是否只由数字组成
'''
Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.
'''
a = '123'
print(a.isdigit())#True

b = 'shaw'
print(b.isdigit())#False

c = '123shaw'
print(c.isdigit())#False

'''
怎样将一个字符串转为数字才安全
'''
s = '12345a'
if s.isdigit():
    print(int(s))
else:
    print(s,' is not a num')

try:
    print(int(s))
except Exception as e:
    print(repr(e))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值