-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcommas
executable file
·42 lines (32 loc) · 1.09 KB
/
commas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python3
# Read a number from STDIN, and insert underscores into it.
# Author: Matt Post (@mjpost)
import sys
def main(args):
for line in sys.stdin:
num = line.strip()
# Insert commas into the number.
num = insert_commas(num, args.separator)
# Print the number.
print(num)
def insert_commas(prefix, separator):
# Insert commas into the number.
# First, reverse the number.
if "." in prefix:
prefix, suffix = prefix.split('.')
suffix = f".{suffix}"
else:
suffix = ""
prefix = prefix[::-1]
# Next, insert commas every three characters.
prefix = separator.join(prefix[i:i+3] for i in range(0, len(prefix), 3))
# Finally, reverse the number again.
prefix = prefix[::-1]
# Return the number.
return prefix + suffix
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Insert commas into a number.')
parser.add_argument('--separator', '-s', default='_', help='Separator to use (default: "_")')
args = parser.parse_args()
main(args)