python判断字符串为10进制数

python字符串常用的判断函数很多,有如下8种,可惜没有能直接判断字符串是否为10进制数的函数数,但是实际工作中我们会遇到需要判断字符串是否为10进制数的场景。
1、str.isalnum() 所有字符都是数字或者字母
2、str.isdecimal() 所有字符都是十进制数字
3、str.isdigit() 所有字符都是数字
4、str.isalpha() 所有字符都是字母
5、str.islower() 所有字符都是小写
6、str.isupper() 所有字符都是大写
7、str.istitle() 所有单词都是首字母大写
8、str.isspace() 所有字符都是空白字符、\t、\n、\r

>>> s = '123abc5'
>>> s.isalnum()
True
>>> s.isalpha()
False
>>> s.islower()
True
>>> s.isspace()
False
>>> 
>>> s1 = '123.456'
>>> s1.isdecimal()
False
>>> s1.isdigit()
False
>>> 
>>> s1.islower()
False
>>> 
>>> s2 = '123456'
>>> s2.isdigit()
True
>>> s2.isdecimal()
True
>>> 

遇上小数点后,str.isdecimal()和str.isdigit()判断不出来,此时可以用正则表达式来判断。

>>> import re
>>> pattern = r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$'
>>> re.match(pattern, s)
>>> re.match(pattern, s1)

>>> re.match(pattern, s2)

>>> re.match(pattern, 'nan')
>>> re.match(pattern, '-inf')
>>> re.match(pattern, '六')
>>> re.match(pattern, '0')

>>> re.match(pattern, '-12.110031')

>>> 

常用的正则判断式有:

\s 匹配任意空白字符,等价于 [\t\n\r\f].
\Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。
\b

匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。

1. Find any hexadecimal number in a larger body of text
\b[0-9a-fA-F]+\b

2. Check whether a text string holds just a hexadecimal number
\A[0-9a-fA-F]+\Z

3. Find a hexadecimal number with a 0x prefix
\b0x[0-9a-fA-F]+\b

4. Find a hexadecimal number with an &H prefix
&H[0-9a-fA-F]+\b

5. Find a hexadecimal number with an H suffix
\b[0-9a-fA-F]+H\b

6. Find a hexadecimal byte value or 8-bit number
\b[0-9a-fA-F]{2}\b

7. Find a hexadecimal word value or 16-bit number
\b[0-9a-fA-F]{4}\b

8. Find a hexadecimal double word value or 32-bit number
\b[0-9a-fA-F]{8}\b

9. Find a hexadecimal quad word value or 64-bit number
\b[0-9a-fA-F]{16}\b

10. Find a string of hexadecimal bytes (i.e., an even number of hexadecimal digits)
\b(?:[0-9a-fA-F]{2})+\b

11. Find any hexadecimal number standalone in a larger body of text
(?:^|(?<=\s))[0-9a-fA-F]+(?=$|\s)

 

2进制,8进制,10进制,16进制在python中的表示方法和互相转换函数

2进制:满2进1   , 0b10
8进制:满8进1   , 0o10
10进制:满10进1  , 10
16进制:满16进1  , 0x10
时间满60进1
bin()  转2进制方法
int()   转10进制方法
oct()  转8进制方法
hex()  转16进制方法

>>> bin(20)
'0b10100'
>>> bin(0o45)
'0b100101'
>>> bin(0x1F)
'0b11111'
>>> int(0b10)
2
>>> int(0b11)
3
>>> int(0o34)
28
>>> int(0x1f)
31
>>> int(0x3f)
63
>>> hex(100)
'0x64'
>>> hex(0x1f)
'0x1f'
>>> hex(0o45)
'0x25'
>>> hex(0b101)
'0x5'
>>> oct(0x45)
'0o105'
>>> oct(0b101)
'0o5'


参考:
https://blog.csdn.net/Gordennizaicunzai/article/details/105618829
https://www.csdn.net/gather_20/MtjaIgwsNTkxLWJsb2cO0O0O.html
 

你可能感兴趣的:(python)