My code's purpose is to list all possible 4 digit numbers (0000-9999), which it does easily.
i = 0
gen = []
while i <= 9999:
gen.append(i)
i = i + 1
for cycle in gen:
format(cycle, '04')
However, it prints each number on its own line, and I would like it to print in one big string. So my question is how do I join my list of integers so that it prints in one big string? I'm running Python 3.3 on Windows.
So, there is a function range
, which builds a generator for you; for example: range(0,10000)
will generate 10,000 integers starting from 0 (0 to 9999 inclusive).
Note the range object is not a list, it's a function that will generate a list. You could make a list by doing:
list(range(0,10000))
Which gets you something like
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... 9999]
You can use a list comprehension to format each entry in the list:
[format(x, '04') for x in range(0,10000)]
Which gives you a list of strings like:
['0000', '0001', '0002', '0003', '0004', ...
Then to join a list of strings together, there is a function called join
. You want to put the empty string between each number, so you call it like this:
"".join([format(x, '04') for x in range(0,10000)])
And you get your output:
00000001000200030004000500060007 ... 9999
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments