문자열을 float 또는 int로 해석하려면 어떻게 해야 하나요?
- 「 」를 해야 ?
str
로로 합니다.float
무슨 일입니까?"545.2222" → 545.2222
- 「 」를 해야 ?
str
로로 합니다.int
무슨 일입니까?"31" → 31
반대의 경우 Python에서 정수를 문자열로 변환 및 반올림하지 않고 플로트를 문자열로 변환을 참조하십시오.
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
문자열이 플로트인지 확인하는 Python 메서드:
def is_float(value):
try:
float(value)
return True
except:
return False
한 이름은 is_convertible_to_float(value)
Python의 플로트(float)와 플로트(float)가 아닌 것은 다음과 같습니다.
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False 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,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade 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 allowed
u'四' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**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
숫자가 뭔지 알 것 같아?넌 네가 생각하는 것만큼 잘하지 못해!별로 놀랍지도 않아요.
생명에 중요한 소프트웨어에서는 이 코드를 사용하지 마십시오.
이러한 방법으로 광범위한 예외를 포착하면 카나리아를 죽이고 예외를 게걸스럽게 먹어치우면 문자열로서 유효한 플로트가 false를 반환할 가능성이 매우 희박해집니다.float(...)
문자열의 내용과 무관한 수천 가지 이유 중 하나로 인해 코드 행이 실패할 수 있습니다.그러나 Python과 같이 생명에 중요한 소프트웨어를 오리타입을 사용하는 프로토타입 언어로 작성한다면 훨씬 더 큰 문제가 발생합니다.
def num(s):
try:
return int(s)
except ValueError:
return float(s)
이것은 여기서 언급할 가치가 있는 또 다른 방법인 ast.literal_eval입니다.
이것은 값을 직접 구문 분석할 필요 없이 신뢰할 수 없는 소스의 Python 식을 포함하는 문자열을 안전하게 평가하는 데 사용할 수 있습니다.
즉, 안전한 '평가'입니다.
>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31
현지화 및 쉼표
.float("545,545.2222")
하다. 의 방법을 하세요.locale
문자열을 숫자로 변환하고 쉼표를 올바르게 해석합니다.locale.atof
method는 로케일이 원하는 번호 규칙에 대해 설정되면 한 번에 플로트로 변환됩니다.
예 1 - 미국 번호 표기법
미국과 영국에서는 쉼표를 수천 개의 구분 기호로 사용할 수 있습니다.미국 로케일을 사용하는 예에서는 콤마는 구분자로 올바르게 처리됩니다.
>>> 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
>>>
예 2 - 유럽 번호 표기법
세계 대부분의 국가에서 쉼표는 마침표 대신 소수점 기호로 사용됩니다.프랑스어 로케일을 사용하는 예에서는 콤마는 소수점 마크로 올바르게 처리됩니다.
>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222
법locale.atoi
또한 사용할 수 있지만 인수는 정수여야 합니다.
float(x) if '.' in x else int(x)
서드파티 모듈을 싫어하지 않으면 fastnumbers 모듈을 확인해 보십시오.fast_real이라는 함수가 제공되어 이 질문이 요구하는 것을 정확하게 수행하며 순수 Python 구현보다 더 빠르게 수행할 수 있습니다.
>>> 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
사용자 코델로직과 할리는 맞지만 문자열이 정수(예를 들어 545)라는 것을 알고 있으면 먼저 캐스팅하지 않고 int('545')를 호출할 수 있습니다.
문자열이 목록에 있는 경우 맵 기능을 사용할 수도 있습니다.
>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>
모두 같은 타입일 경우에만 좋습니다.
Python에서는 "545.2222"와 같은 숫자 문자열을 대응하는 float 값인 542.2222로 해석하려면 어떻게 해야 합니까? 아니면 문자열 "31"을 정수, 31로 해석할까요?float 문자열을 float로 해석하는 방법과 int 문자열을 int로 해석하는 방법(별도)
따로따로 부탁하는 게 좋아요.그것들을 혼합하고 있는 경우는, 나중에 문제를 일으킬 가능성이 있습니다.간단한 답은 다음과 같습니다.
"545.2222"
★★★★★★★★★★★★★★★★★★:
>>> float("545.2222")
545.2222
"31"
다음 중 하나:
>>> int("31")
31
기타 변환, 문자열 및 리터럴과의 변환:
다양한 베이스로부터의 변환입니다.기본값은 10입니다.Python이 리터럴에 기대하는 것을 프리픽스(아래 참조)에 부가하거나 프리픽스를 삭제할 수 있습니다.
>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31
알 수 프레픽스를 , 은 이 를 사용할 수 .0
★★★★★★★★★★★★★★★★★★:
>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31
다른 베이스로부터의 10진수 이외의 리터럴(정수)
다만, 자신의 코드가 하드 코드화된 특정의 값을 명확하게 나타내도록 하는 것이 동기라면, 베이스로부터 변환할 필요는 없습니다.Python이 올바른 구문을 사용해 자동적으로 하도록 할 수 있습니다.
apropos 프리픽스를 사용하면 다음 리터럴을 가진 정수로 자동 변환할 수 있습니다.다음은 Python 2 및 3에 적용됩니다.
, 프리픽스 「」, 「」0b
>>> 0b11111
31
, 프리픽스 ''', '''0o
>>> 0o37
31
, 프리픽스 16, '''"0x
>>> 0x1f
31
이는 이진 플래그, 코드의 파일 권한 또는 색상의 16진수 값을 설명할 때 유용합니다(예: 따옴표 없음).
>>> 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와 호환되게 하다
0으로 시작하는 정수가 있는 경우 Python 2에서는 이것이 (사용되지 않는) 8진수 구문입니다.
>>> 037
31
값이 다음과 같아야 할 것 같기 때문에 좋지 않습니다.37
3에서는 Python 3 a a a 、 Python 3 、 Python 3 、 Python 3 、 Python 3 、SyntaxError
:
>>> 037
File "<stdin>", line 1
037
^
SyntaxError: invalid token
을 Python 2의 합니다.0o
★★★★★★★★★★★★★★★★★★:
>>> 0o37
31
그 질문은 좀 오래된 것 같다.그러나 유사한 것을 만드는 함수 parseStr을 제안합니다.즉, 정수 또는 플로트를 반환하고, 지정된 ASCII 문자열을 어느 것에도 변환할 수 없는 경우 변경되지 않은 상태로 반환합니다.물론 코드는 원하는 작업만 수행하도록 조정될 수 있습니다.
>>> 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'
float("545.2222")
그리고.int(float("545.2222"))
YAML 파서는 문자열의 데이터 유형을 파악하는 데 도움이 됩니다.사용하다yaml.load()
를 사용하여type(result)
유형을 테스트하려면:
>>> import yaml
>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>
>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>
>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>
이 기능을 사용하고 있습니다.
import ast
def parse_str(s):
try:
return ast.literal_eval(str(s))
except:
return
문자열을 해당 유형으로 변환합니다.
value = parse_str('1') # Returns Integer
value = parse_str('1.5') # Returns Float
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):
"""num(s)
num(3),num(3.7)-->3
num('3')-->3, num('3.7')-->3.7
num('3,700')-->ValueError
num('3a'),num('a3'),-->ValueError
num('3e4') --> 30000.0
"""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise ValueError('argument is not a string of number')
사용할 수 있습니다.json.loads
:
>>> import json
>>> json.loads('123.456')
123.456
>>> type(_)
<class 'float'>
>>>
보다시피, 그것은 하나의 타입이 된다.float
.
이 작업을 올바르게 수행하려면 반올림을 고려해야 합니다.
즉, -int(5.1)
=> 5int(5.6)
=> 5 -- 틀렸습니다.6이 되어야 하기 때문에 그렇게 하고 있습니다.int(5.6 + 0.5)
=> 6
def convert(n):
try:
return int(n)
except ValueError:
return float(n + 0.5)
때때로 번호로 캐스팅하기 전에 스트링을 준비하고 정규화해야 하기 때문에 regex에 대해 아무도 언급하지 않은 것이 놀랍습니다.
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
다음 함수에 문자열을 전달합니다.
def string_to_number(str):
if("." in str):
try:
res = float(str)
except:
res = str
elif(str.isdigit()):
res = int(str)
else:
res = str
return(res)
전달된 항목에 따라 int, float 또는 string이 반환됩니다.
int인 문자열
print(type(string_to_number("124")))
<class 'int'>
뜨개질 끈
print(type(string_to_number("12.4")))
<class 'float'>
스트링인 스트링
print(type(string_to_number("hello")))
<class 'str'>
뜨개질 같은 끈
print(type(string_to_number("hel.lo")))
<class 'str'>
로.typecast
Python에서는 문자열(또는 캐스트하려는 값)을 매개 변수로 전달하여 유형의 생성자 함수를 사용합니다.
예를 들어 다음과 같습니다.
>>>float("23.333")
23.333
뒤에서 Python은 오브젝트를 호출하고 있습니다.__float__
method: 매개 변수의 부동 표현을 반환합니다.이것은 특히 강력합니다.클래스를 사용하여 자신의 유형을 정의할 수 있기 때문입니다.__float__
사용하여 부체에 주조할 수 있는 방법float(myobject)
.
16진수, 8진수, 2진수, 10진수 및 플로트를 처리합니다.
이 솔루션은 숫자에 대한 모든 문자열 규칙을 처리합니다(내가 알고 있는 모든 것).
def to_number(n):
''' Convert any number representation to a number
This 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' prefix
return int('0o' + n, 0)
except:
return float(n)
이 테스트 케이스의 출력은, 내가 말하는 것을 나타내고 있습니다.
======================== CAPTURED OUTPUT =========================
to_number(3735928559) = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0") = 0 == 0
to_number(100) = 100 == 100
to_number("42") = 42 == 42
to_number(8) = 8 == 8
to_number("0o20") = 16 == 16
to_number("020") = 16 == 16
to_number(3.14) = 3.14 == 3.14
to_number("2.72") = 2.72 == 2.72
to_number("1e3") = 1000.0 == 1000
to_number(0.001) = 0.001 == 0.001
to_number("0xA") = 10 == 10
to_number("012") = 10 == 10
to_number("0o12") = 10 == 10
to_number("0b01010") = 10 == 10
to_number("10") = 10 == 10
to_number("10.0") = 10.0 == 10
to_number("1e1") = 10.0 == 10
테스트는 다음과 같습니다.
class test_to_number(unittest.TestCase):
def test_hex(self):
# All of the following should be converted to an integer
#
values = [
# HEX
# ----------------------
# Input | Expected
# ----------------------
(0xDEADBEEF , 3735928559), # Hex
("0xFEEDFACE", 4277009102), # Hex
("0x0" , 0), # Hex
# Decimals
# ----------------------
# Input | Expected
# ----------------------
(100 , 100), # Decimal
("42" , 42), # Decimal
]
values += [
# Octals
# ----------------------
# Input | Expected
# ----------------------
(0o10 , 8), # Octal
("0o20" , 16), # Octal
("020" , 16), # Octal
]
values += [
# Floats
# ----------------------
# Input | Expected
# ----------------------
(3.14 , 3.14), # Float
("2.72" , 2.72), # Float
("1e3" , 1000), # Float
(1e-3 , 0.001), # Float
]
values += [
# All ints
# ----------------------
# Input | Expected
# ----------------------
("0xA" , 10),
("012" , 10),
("0o12" , 10),
("0b01010" , 10),
("10" , 10),
("10.0" , 10),
("1e1" , 10),
]
for _input, expected in values:
value = to_number(_input)
if isinstance(_input, str):
cmd = 'to_number("{}")'.format(_input)
else:
cmd = 'to_number({})'.format(_input)
print("{:23} = {:10} == {:10}".format(cmd, value, expected))
self.assertEqual(value, expected)
a = int(float(a)) if int(float(a)) == float(a) else float(a)
이것은 https://stackoverflow.com/a/33017514/5973334의 수정 버전입니다.
이것은 문자열을 해석하려고 시도하고 다음 중 하나를 반환합니다.int
또는float
문자열이 무엇을 나타내느냐에 따라 달라집니다.구문 분석 예외가 발생하거나 예기치 않은 동작이 발생할 수 있습니다.
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
이것은 오래된 질문으로 이미 많은 답변을 얻고 있습니다.다만, 혼재된 정수와 플로트를 취급하고 있어 혼재된 데이터를 일관되게 취급하고 싶다면, 적절한 docstring을 사용한 솔루션을 다음에 제시하겠습니다.
def parse_num(candidate):
"""parse string to number if possible
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 0
if float_value.is_integer():
return int(float_value)
# end of the optional part
return float_value
# test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)
출력:
Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']
After:
[34.77, -13, None, 8990, 76323454]
용도:
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()
이것이 내가 생각해 낼 수 있는 가장 종교적인 방법이다.
용도:
>>> str_float = "545.2222"
>>> float(str_float)
545.2222
>>> type(_) # Check its type
<type 'float'>
>>> str_int = "31"
>>> int(str_int)
31
>>> type(_) # Check its type
<type 'int'>
이든 변환해 입니다.object
뿐만 str
부터 )까지int
★★★★★★★★★★★★★★★★★」float
제공된 실제 문자열이 다음과 같은지 여부에 따라 달라집니다. int
★★★★★★★★★★★★★★★★★」float
, 둘 다 있는 __float
★★★★★★★★★★★★★★★★★」__int__
로는 「」, 「」를 __float__
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 = True
elif isinstance(x, str):
is_str = True
is_other = not any([is_num, is_str])
if is_num:
res = x
elif is_str:
is_float, is_int, is_char = [False]*3
try:
res = float(x)
if '.' in x:
is_float = True
else:
is_int = True
except ValueError:
res = x
is_char = True
else:
if num_type == 'asis':
funcs = [int, float]
else:
funcs = [num_type]
for func in funcs:
try:
res = func(x)
break
except TypeError:
continue
else:
res = x
int 및 float 메서드를 사용하여 문자열을 정수와 float로 변환할 수 있습니다.
s="45.8"
print(float(s))
y='67'
print(int(y))
숫자와 문자를 조합한 경우:
string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"
첫 번째 Import re:
import re
#for get integer part:
print(int(re.search(r'\d+', string_for_int).group())) #498
#for get float part:
print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
간단한 모델:
value1 = "10"
value2 = "10.2"
print(int(value1)) #10
print(float(value2)) #10.2
여기 당신의 질문에 대한 또 다른 해석이 있습니다(힌트: 모호합니다).다음과 같은 것을 찾고 있을 가능성이 있습니다.
def parseIntOrFloat( aString ):
return eval( aString )
이렇게 작동하는데...
>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545
를 들어 은 예를 , 문자열이 될 수 ."import os; os.abort()"
그러나 문자열의 출처에 대한 어떠한 배경도 없이, 가능성은 이론적인 추측일 수 있다.질문이 모호하기 때문에 이 취약성이 실제로 존재하는지 여부가 전혀 명확하지 않습니다.
언급URL : https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int
'programing' 카테고리의 다른 글
JavaScript를 사용하여 양식을 제출하려면 어떻게 해야 합니까? (0) | 2022.09.16 |
---|---|
MySQL의 Connector/J는 MariaDB에서 작동합니까? (0) | 2022.09.16 |
MySql 쿼리 선택에서 NULL을 빈 문자열로 바꾸기 (0) | 2022.09.16 |
MariaDB / Larabel 5 태그 보관에 최적인 엔진 (0) | 2022.09.16 |
최소 유효 JSON은 얼마입니까? (0) | 2022.09.16 |