>>> import string>>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \... int(x) or x.isalnum() and x or \... len(set(string.punctuation).intersection(x)) == 1 and \... x.count('.') == 1 and float(x) or x>>> parseStr('123')123>>> parseStr('123.3')123.3>>> parseStr('3HC1')'3HC1'>>> parseStr('12.e5')1200000.0>>> parseStr('12$5')'12$5'>>> parseStr('12.2.2')'12.2.2'
val is_float(val) Note-------------------- ---------- --------------------------------"" False Blank string"127" True Passed stringTrue True Pure sweet Truth"True" False Vile contemptible lieFalse True So false it becomes true"123.456" True Decimal" -127 " True Spaces trimmed"\t\n12\r\n" True whitespace ignored"NaN" True Not a number"NaNanananaBATMAN" False I am Batman"-iNF" True Negative infinity"123.E4" True Exponential notation".1" True mantissa only"1_2_3.4" False Underscores not allowed"12 34" False Spaces not allowed on interior"1,234" False Commas gtfou'\x30' True Unicode is fine."NULL" False Null is not special0x3fade True Hexadecimal"6e7777777777777" True Shrunk to infinity"1.797693e+308" True This is max value"infinity" True Same as inf"infinityandBEYOND" False Extra characters wreck it"12.34.56" False Only one dot allowedu'四' False Japanese '4' is not a float."#56" False Pound sign"56%" False Percent of what?"0E0" True Exponential, move dot 0 places0**0 True 0___0 Exponentiation"-5e-5" True Raise to a negative number"+1e1" True Plus is OK with exponent"+1e1^5" False Fancy exponent not interpreted"+1e1.3" False No decimals in exponent"-+1" False Make up your mind"(1)" False Parenthesis is bad
>>> 0b10101 # binary flags21>>> 0o755 # read, write, execute perms for owner, read & ex for group & others493>>> 0xffffff # the color, white, max values for red, green, and blue16777215
使模棱两可的Python 2八进制与Python 3兼容
如果您看到一个以0开头的整数,在Python 2中,这是(已弃用的)八进制语法。
>>> 03731
这很糟糕,因为它看起来应该是37。所以在Python 3中,它现在引发了SyntaxError:
>>> 037File "<stdin>", line 1037^SyntaxError: invalid token
def num(s):"""num(s)num(3),num(3.7)-->3num('3')-->3, num('3.7')-->3.7num('3,700')-->ValueErrornum('3a'),num('a3'),-->ValueErrornum('3e4') --> 30000.0"""try:return int(s)except ValueError:try:return float(s)except ValueError:raise ValueError('argument is not a string of number')
def conv_to_num(x, num_type='asis'):'''Converts an object to a number if possible.num_type: int, float, 'asis'Defaults to floating point in case of ambiguity.'''import numbers
is_num, is_str, is_other = [False]*3
if isinstance(x, numbers.Number):is_num = Trueelif isinstance(x, str):is_str = True
is_other = not any([is_num, is_str])
if is_num:res = xelif is_str:is_float, is_int, is_char = [False]*3try:res = float(x)if '.' in x:is_float = Trueelse:is_int = Trueexcept ValueError:res = xis_char = True
else:if num_type == 'asis':funcs = [int, float]else:funcs = [num_type]
for func in funcs:try:res = func(x)breakexcept TypeError:continueelse:res = x
def to_number(n):''' Convert any number representation to a numberThis covers: float, decimal, hex, and octal numbers.'''
try:return int(str(n), 0)except:try:# Python 3 doesn't accept "010" as a valid octal. You must use the# '0o' prefixreturn int('0o' + n, 0)except:return float(n)
string_for_int = "498 results should get"string_for_float = "498.45645765 results should get"
首次导入关于:
import re
# For getting the integer part:print(int(re.search(r'\d+', string_for_int).group())) #498
# For getting the float part:print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
def parse_num(candidate):"""Parse string to number if possibleIt work equally well with negative and positive numbers, integers and floats.
Args:candidate (str): string to convert
Returns:float | int | None: float or int if possible otherwise None"""try:float_value = float(candidate)except ValueError:return None
# Optional part if you prefer int to float when decimal part is 0if float_value.is_integer():return int(float_value)# end of the optional part
return float_value
# Testcandidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']res_list = list(map(parse_num, candidates))print('Before:')print(candidates)print('After:')print(res_list)
def string_to_int_or_float(s):try:f = float(s) # replace s with str(s) if you are not sure that s is a stringexcept ValueError:print("Provided string '" + s + "' is not interpretable as a literal number.")raisetry:i = int(str(f).rstrip('0').rstrip('.'))except:return freturn i
s = '542.22'
f = float(s) # This converts string data to float data with a decimal pointprint(f)
i = int(f) # This converts string data to integer data by just taking the whole number part of itprint(i)