-1

This is my code:

line = 'hi'
while line != '':
    line = input('Sentence: ')
    if '!' in line:
        if list(line)[0] == '!':
            reversed_text = ''
            last_index = len(line) - 1
            for i in range(last_index, -1, -1):
                reversed_text += line[i]
            print(reversed_text)
        else:
            print(line)
    else:
        print(line)

It seems to be adding an extra blank line when the user inputs nothing, and I'm not sure how to stop it. Any suggestions?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
S.Though
  • 1
  • 1
  • Welcome to Stack Overflow. Have you [searched for an answer](https://www.google.co.uk/search?q=python+print+without+newline)? This question is quite common. – Peter Wood Nov 22 '15 at 14:44

1 Answers1

-1

basically the newline is a result of your print printing an empty line. Take this code for example:

>>> a = input()    # user presses enter (blank line)
>>> a
''
>>> print(a)
                   # a newline introduced by `print` function
>>>

we can however override this default behavior of print
print as the form print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])

>>> a = ''
>>> print(a, end='')
>>> 

To sum up, all you need to do in your code is, replace print(<somevalue>) with print(<somevalue>, end='')

Ishan Khare
  • 1,745
  • 4
  • 28
  • 59