파이썬 123,456.908에서 부동 처럼 문자열을 어떻게 변환 할 수 123456.908있습니까?
답변:
다음 ,과 replace()같이 제거하십시오 .
float("123,456.908".replace(',',''))
python cd_size = float("737,280,000".replace(',','')) (실제로 int 사용)
setlocale애초에있는 이유 입니다.
... 또는 쉼표를 필터링 할 쓰레기로 처리하는 대신 전체 문자열을 float의 현지화 된 형식으로 처리하고 현지화 서비스를 사용할 수 있습니다.
from locale import atof, setlocale, LC_NUMERIC
setlocale(LC_NUMERIC, '') # set to your default locale; for me this is
# 'English_Canada.1252'. Or you could explicitly specify a locale in which floats
# are formatted the way that you describe, if that's not how your locale works :)
atof('123,456') # 123456.0
# To demonstrate, let's explicitly try a locale in which the comma is a
# decimal point:
setlocale(LC_NUMERIC, 'French_Canada.1252')
atof('123,456') # 123.456
Extension modules should never call setlocale()
atof strings 의 내장 메서드입니다 . 여기서 제가 사용 atof하고있는 것은 locale표준 라이브러리 모듈 의 함수 로, 전혀 사용되지 않습니다.
locale.atof
로케일을 모르고 모든 종류의 숫자를 구문 분석하려면 이 parseNumber(text)함수를 사용 하십시오 . 완벽하지는 않지만 대부분의 경우를 고려하십시오.
>>> parseNumber("a 125,00 €")
125
>>> parseNumber("100.000,000")
100000
>>> parseNumber("100 000,000")
100000
>>> parseNumber("100,000,000")
100000000
>>> parseNumber("100 000 000")
100000000
>>> parseNumber("100.001 001")
100.001
>>> parseNumber("$.3")
0.3
>>> parseNumber(".003")
0.003
>>> parseNumber(".003 55")
0.003
>>> parseNumber("3 005")
3005
>>> parseNumber("1.190,00 €")
1190
>>> parseNumber("1190,00 €")
1190
>>> parseNumber("1,190.00 €")
1190
>>> parseNumber("$1190.00")
1190
>>> parseNumber("$1 190.99")
1190.99
>>> parseNumber("1 000 000.3")
1000000.3
>>> parseNumber("1 0002,1.2")
10002.1
>>> parseNumber("")
>>> parseNumber(None)
>>> parseNumber(1)
1
>>> parseNumber(1.1)
1.1
>>> parseNumber("rrr1,.2o")
1
>>> parseNumber("rrr ,.o")
>>> parseNumber("rrr1rrr")
1
여기 내가 당신을 위해 쓴 간단한 방법이 있습니다. :)
>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908
re그러한 작업에 큰 망치입니다.
float(number)설명적인 터치 때문에 좋아 합니다. +1 ;-)
그냥 교체 ,교체로 ().
f = float("123,456.908".replace(',',''))
print(type(f)
type ()은 그것이 float로 변환되었음을 보여줍니다.
다양한 통화 형식에 대한 더 나은 솔루션 :
def text_currency_to_float(text):
t = text
dot_pos = t.rfind('.')
comma_pos = t.rfind(',')
if comma_pos > dot_pos:
t = t.replace(".", "")
t = t.replace(",", ".")
else:
t = t.replace(",", "")
return(float(t))
locale모듈 을 사용하는 것입니다. 다른 모든 것은 미래에 문제를 일으킬 수있는 매우 불쾌한 해킹 일뿐입니다.