Bhavik Joshi February 2016

How to ignore the next line in python

I am trying to print something like this

*
* *
* * *
* * * *

Here is my code

while 1:
    n=int(input("Enter the N"))
    if n<3:
        print("Wrong Input")
        continue
    else:
        for i in range(1,n+1):
            for j in range(1,i+1):
                print("x")

I refer to this question but I am not able to achieve this. Can you please help me how can I achieve this? Thank you

Answers


Anton Protopopov February 2016

Example:

for i in range(5): 
     print('* '* i)

*
* *
* * *
* * * *

EDIT

Or you could use map functions which is faster:

print('\n'.join(map(lambda x: '* ' * x, range(5))))

Timing

In [25]: %timeit print('\n'.join(map(lambda x: '* ' * x, range(5))))
1000 loops, best of 3: 289 us per loop

In [26]: %timeit for i in range(5): print('* '*i)
1000 loops, best of 3: 444 us per loop


Iron Fist February 2016

Or something like this as well might work:

>>> n = 5
>>> s = '\n'.join('*' * i for i in range(5))
>>> print(s)

*
**
***
****

Or wrap it in a function definition and pass it any character you want with any number you need:

>>> def my_print(c, n):
        s = '\n'.join(c * i for i in range(n+1))
        return s

>>> my_string = my_print('^', 10)
>>> print(my_string)


^
^^
^^^
^^^^
^^^^^
^^^^^^
^^^^^^^
^^^^^^^^
^^^^^^^^^
^^^^^^^^^^

Post Status

Asked in February 2016
Viewed 1,426 times
Voted 8
Answered 2 times

Search




Leave an answer