user391339
user391339

Reputation: 8785

Shortest way to add more characters to a string with each successive line

I want to write

Wow!
Wow!!
Wow!!!
Wow!!!!
... etc

in the simplest way possible.

print "Wow%s\n"%"!"*3

Is as close I can get without a loop (but it doesn't add the exclamations).

If you can't do this in python without a loop, I am curious if there is a language that would allow it.

Upvotes: 0

Views: 69

Answers (3)

th3an0maly
th3an0maly

Reputation: 3510

You need to enclose your format string like this:

print "Wow%s\n" % ("!"*3)

Upvotes: 0

Bhargav Rao
Bhargav Rao

Reputation: 52161

Use join and a generator expression (avoiding the loop is not possible)

>>> print"\n".join("Wow{}".format('!'*i) for i in range(1,4))
Wow!
Wow!!
Wow!!!
Wow!!!!

If you really want to avoid for keyword

>>> n = 4
>>> word = "Wow"
>>> symb = "!"
>>> print("\n".join(map(lambda x:x[0]+x[1],zip([word]*(n-1),map(lambda i:symb*i,range(1,n))))))
Wow!
Wow!!
Wow!!!

Upvotes: 4

zmbq
zmbq

Reputation: 39033

You won't be able to do this without some sort of loop, as you need to change the number of exclamation points from 1 to infinity, and for that you need a loop.

You can do that without writing the loop yourself, though:

["Wow" + '!'*n for n in range(500000000)]

There's still a loop in there.

Upvotes: 2

Related Questions