JavaScript
x
2
1
example_strings = ["10.43 KB", "11 GB", "343.1 MB"]
2
I want to convert all this strings into bytes. So far I came up with this:
JavaScript
1
13
13
1
def parseSize(size):
2
if size.endswith(" B"):
3
size = int(size.rstrip(" B"))
4
elif size.endswith(" KB"):
5
size = float(size.rstrip(" KB")) * 1000
6
elif size.endswith(" MB"):
7
size = float(size.rstrip(" MB")) * 1000000
8
elif size.endswith(" GB"):
9
size = float(size.rstrip(" GB")) * 10000000000
10
elif size.endswith(" TB"):
11
size = float(size.rstrip(" TB")) * 10000000000000
12
return int(size)
13
But I don’t like it and also I don’t think it works. I could find only modules that do the opposite thing.
Advertisement
Answer
Here’s a slightly prettier version. There’s probably no module for this, just define the function inline. It’s very small and readable.
JavaScript
1
19
19
1
units = {"B": 1, "KB": 10**3, "MB": 10**6, "GB": 10**9, "TB": 10**12}
2
3
# Alternative unit definitions, notably used by Windows:
4
# units = {"B": 1, "KB": 2**10, "MB": 2**20, "GB": 2**30, "TB": 2**40}
5
6
def parse_size(size):
7
number, unit = [string.strip() for string in size.split()]
8
return int(float(number)*units[unit])
9
10
11
example_strings = ["10.43 KB", "11 GB", "343.1 MB"]
12
13
for example_string in example_strings:
14
print(parse_size(example_string))
15
16
10680
17
11811160064
18
359766426
19
(Note that different places use slightly different conventions for the definitions of KB, MB, etc — either using powers of 10**3 = 1000
or powers of 2**10 = 1024
. If your context is Windows, you will want to use the latter. If your context is Mac OS, you will want to use the former.)