jinwon2
jinwon2

Reputation: 84

Is there a way to make a string with sequential numbers without using a for-loop?

I would ike to make a string with digits like this: 123456789.
I can write this easily with a for loop.

x = ""
for i in range(1, 10):
    x += str(i)

However, I would like to write this with no explicit for loops.
Are there any creative ways, to do this?

Upvotes: 1

Views: 127

Answers (3)

solid.py
solid.py

Reputation: 2812

Should you wish to use the itertools module of python you could do something like this:

from itertools import takewhile, count
x = ''
x = ''.join(map(str, takewhile(lambda x: x < 10, count(1))))
print(x)

When the above code snippet runs, it prints:

123456789

Upvotes: 1

Tomerikoo
Tomerikoo

Reputation: 19414

Just for the sake of it, you could use a recursive function if you really wanted:

def stringer(n):
    if n <= 1:
        return '1'

    return stringer(n-1) + str(n)

What the function does is return the string 123...n by calling itself recursively, decreasing n each time until reaching 1, and then building the string on the way back.

If called as print(stringer(9)) this will give:

123456789

No loops there, just a nice call stack

Upvotes: 3

Timo Frionnet
Timo Frionnet

Reputation: 484

You could create the range as follows:

rangeToConvert = range(1, 10)

And than join the list to create a string. Only issue is that the values in the rangeToConvert are ints so you need to convert them to string in order to use the join function.

x = ''.join(map(str, rangeToConvert))

X would be in this case:

'123456789'

Upvotes: 3

Related Questions