>>> import itertools
>>> s = '-1234567'
>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')
Python/2.7 for fun.
파이썬 숫자를 3자리씩 끊어서 출력하기.
qkqhxla1
2018. 8. 13. 10:46
1000같은 숫자를 1,000처럼 출력해야 하는데 뭔가 format이 있을것같았다. 그래서 간단하게 구글링을 해봤는데... 단순히 format으로 출력하는거 말고 별 이상한 방법들이 다 있었다.
답변들이 흥미로워서 링크를 공유해 봄...
https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators
재밌는 답변 두개만 가져와봄..
가장 복잡하며 가독성 제로의 답변.
정규식 수업.
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.5f" % val)
re.sub(pattern, repl, string)
pattern = \
"(\d) # Find one digit...
(?= # that is followed by...
(\d{3})+ # one or more groups of three digits...
(?!\d) # which are not followed by any more digits.
)",
repl = \
r"\1,", # Replace that one digit by itself, followed by a comma,
# and continue looking for more matches later in the string.
# (re.sub() replaces all matches it finds in the input)
string = \
"%d" % val # Format the string as a decimal to begin with