파이썬 1000단위 콤마 넣는법

조회수 29326회

구글링을 해보니 1000단위마다 콤마를 넣으려고 할 때

number =  12345

number =  format(number, ',')

이것과

import locale

locale.setlocale(locale.LC_ALL, '') 

n = -1234567890.123

s = locale.format('%.3f', n, 1)

이런 방법이 있던데 차이점이 무엇인가요??

1 답변

  • 개발된 목적에서 차이가 있습니다만, 사용에 따라서는 동일한 결과를 얻을 수도 있습니다.

    format

    format 함수는 어떤 값을 포맷팅하는 함수입니다. 예를들어, 2진수, 8진수, 10진수 16진수 표현한다거나, 지수로 표현하거나, %로 표현하는 등, 너비를 n으로 할 때, 빈공간을 0 혹은 공백으로 채운다거나 하는 등의 형식을 정하여, 문자열로 만드는 함수 입니다. (날짜의 경우

    format 함수는 다음과 같은 방법으로 쓸 수 있습니다.

    format(값, "형식규칙") 혹은
    "{형식규칙}".format(값)
    
    print(format(1234, ",")) # 3자리마다 , 추가
    print(format(1234, "E")) # 지수로 표현
    print(format(1234, "X")) # 16진수로 표현
    print(format(1234, "_>-012,.2f"))
    

    위에서 마지막예는 _으로 빈공간을 채우고(첫글자는 채움글자), 오른쪽에 숫자를 맞추며(>문자), 음수일때만 부호 표시하고(-문자), 항상 12자리 맞게 출력하고(012), 3자리마다 , 를 추가하고(,문자), 소수점은 2자리까지인(.2문자) 소수(f문자)로 표현합니다.

    locale.format

    이 함수는 다국어 지원시 사용하는 함수 인데, 통상 숫자 표기의 경우 특히, 통화를 표기할 때, 국가별로 다른 것들이 있습니다. 이러한 것을 국가별로 표현하기 위해서 사용하는 함수 입니다.

    locale.format("형식규칙", 숫자, 통화형식)
    

    질문의 예에서 .3f는 .3은 소수점이하 3자리, f는 소수형태로 표시란 의미입니다. 통화형식(monetary)는 참이면 ,를 추가하고, 거짓이면 ,를 추가하지 않습니다.

    참고.

    locale.format(format, val[, grouping[, monetary]])

    Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.

    If monetary is true, the conversion uses monetary thousands separator and grouping strings.

    Please note that this function will only work for exactly one %char specifier. For whole format strings, use format_string().

    Changed in version 2.5: Added the monetary parameter.

    format(value[, format_spec])

    Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

    format(value, format_spec) merely calls value.format(format_spec).

    New in version 2.6.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)