Printing On a Single Line with A While Loop?


I have an issue I have been trying to overcome for sometime. Firstly, here is my code:

quote = input("Enter a Sentence: ")

a = len(quote)
counter = 0
counter1 = 0
reverse = len(quote)-1

print("The Length of the sentence is",a,"characters long!")

for x in range(0,a):
    if str.isspace(quote[x]) == True:
        counter = counter + 1

print("The Length of the sentence is",a - counter,"characters long (excluding space...)!")

for x in range(0,a):
    if str.isupper(quote[x]) == True:
        counter1 = counter1 + 1

print("The number of Upper Case Characters in the sentence is",counter1,"characters!")

print("The number of Lower Case Characters in the sentence is",a-counter1,"characters long!")

print("The Upper Case Version:")

print("The Lower Case Version:")

print("In Reverse order:")

while reverse >= 0:
    reverse = reverse - 1

This program has been designed to find everything there is about a particular sentence. But if you look at the While loop at the bottom. It works fine, but prints the inverse of the sentence one character under another. Is there a way of putting it all in one line?

Asked By: Raihaan-Tech



quote[::-1] will reverse the string much easier than that while loop 🙂

This is called extended slice notation. There’s three parts to the slice notation, "String"[start_index:end_index:step]

>>> "abcdefg"[0:2]
>>> "abcdefg"[2:3]
>>> "abcdefg"[::2]

Remember that indexes occur before the letter, so:

 a b c d e f g
0 1 2 3 4 5 6 7

If you slice [0:2], you’re getting:

|a b|c d e f g
0 1 2 3 4 5 6

if you slice [2:3] you’re getting:

 a b|c|d e f g
0 1 2 3 4 5 6 7

and the last bit of the slice notation is how many steps you take per index. In my test case I used “2” which means it only throws an index every other number:

 a b c d e f g
0   1   2   3

With the negative slice I used as answer to your problem, it steps backwards instead of forwards, starting at the end instead of the beginning. You need those first two colons to show Python you mean a slice (and not beginning at index -1, which would throw IndexError).

 a b c d e f g
7 6 5 4 3 2 1 0

So it lays the indexes like so, and starts counting from zero until the end of the indexes (the beginning of the string).


Answered By: Adam Smith

Try these changes:

print("In Reverse order:")

charSet = ""

while reverse >= 0:
    charSet = charSet + quote[reverse] 

Answered By: guisantogui

You could use sys.stdout.write(quote[reverse]).

Answered By: J. Owens

If you don’t want print to append a newline, specify an empty end like so:

print("A partial line", end='')
print("... continued!")

Take a look at the docs for more information

Answered By: Rob Starling