Search code examples
pythonstringtextreverse

Python: Print word vertically, horizontally and the same in reverse


I want to print a word in all directions, let's say if I get the word "Newton" the result should be:

NEWTON
E
W
T
O
NOTWEN
O
T
W
E
NEWTON

What I did is the following, but how could I make the user only enter the word once, let's say type with an input, and have the result? in my case I am printing them one by one. Thanks

>>> from itertools import zip_longest
>>> text = "newton".upper()
for x in zip_longest(*text.split(), fillvalue=' '):
    print (' '.join(x))
def reverse(phrase):
    return ' '.join(list(map(lambda x: x[::-1], phrase.split())))

print(reverse("newton").upper())
char = 'newton'.upper()
cont = len(char) - 1
while cont >= 0:
    cont2 = char[cont]
    print(cont2)
    cont -= 1
print("newton".upper())``` 

Solution

  • You can use sep and end parameters to make it a lot easier along with slicing.

    def print_e_shape(s):
        print(s)
        print(*s[1:], sep='\n', end='')
        print(s[-2::-1])
        print(*s[-2::-1], sep='\n', end='')
        print(s[1:])
    
    
    print_e_shape('NEWTON')
    

    Output

    NEWTON
    E
    W
    T
    O
    NOTWEN
    O
    T
    W
    E
    NEWTON