1

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?

1
  • 1
    Any solution that is not x = '123456789' will be some kind of a loop, even if not an explicit one that you can see Commented Mar 15, 2020 at 23:53

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.