Search code examples
pythonjoinlist-comprehension

Python: How do I put a list comprehension in a join function?


How do I put a list comprehension in a join function

I ran this:

q = 1283634
print(f'{" ".join([str(q)[i:i+3] for i in range(len(str(q)),0,3)])}')

and printed

>>>  

but I expected to print

>>> 1 283 634

Can someone explain what I did wrong?


Solution

  • The problem is that your range is wrong. You are using the length of str(q) as the start value and and 0 as the end value. You should do the opposite: range(0, len(str(q), 3). If you wish to iterate backwards, you can use a negative step: range(len(str(q)), 0, -3)

    Remember that range has the form: range(start, stop, step=1), where start is the starting index, stop is the ending index and step is optional and is the increment in index.