# type - python turn to integer

## 如何在Python中將字符串解析為float或int? (15)

"545.2222"浮動：

>>> float("545.2222")
545.2222

"31"為整數：

>>> int("31")
31

# 其他轉換，字符串和文字的字符串轉換：

>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31

>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

### 非小數（即整數）來自其他基地的文字

>>> 0b11111
31

>>> 0o37
31

>>> 0x1f
31

>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215

### 模糊Python 2八進制與Python 3兼容

>>> 037
31

>>> 037
File "<stdin>", line 1
037
^
SyntaxError: invalid token

>>> 0o37
31

## 本地化和逗號

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

Python在一行中有很好的解析靈活性。

str = "545.2222"
print ("int: ", + int(float(a)))
print ("float: ", +(float(a)))

>>> import yaml

>>> a = "545.2222"
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b = "31"
>>> result
31
>>> type(result)
<type 'int'>

>>> c = "HI"
>>> result
'HI'
>>> type(result)
<type 'str'>

def get_int_or_float(v):
number_as_float = float(v)
number_as_int = int(number_as_float)
return number_as_int if number_as_float == number_as_int else
number_as_float

def convert(n):
try:
return int(n)
except ValueError:
return float(n + 0.5)

def num(s):
try:
for each in s:
yield int(each)
except ValueError:
yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()

>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int

import re
def parseNumber(value, as_int=False):
try:
number = float(re.sub('[^.\-\d]', '', value))
if as_int:
return int(number + 0.5)
else:
return number
except ValueError:
return float('nan')  # or None if you wish

parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0

import numbers
def is_number(value):
return isinstance(value, numbers.Number)
# will work with int, float, long, Decimal

>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>

>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31

def parseIntOrFloat( aString ):
return eval( aString )

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

def get_int_or_float(v):
number_as_float = float(v)
number_as_int = int(number_as_float)
return number_as_int if number_as_float == number_as_int else number_as_float

def num(s):
try:
return int(s)
except ValueError:
return float(s)

float(x) if '.' in x else int(x)