Question

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(str.upper(quote[0:a]))

print("The Lower Case Version:")
print(str.lower(quote[0:a]))

print("In Reverse order:")

while reverse >= 0:
    print(quote[reverse])
    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?

Was it helpful?

Solution

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]
'ab'
>>> "abcdefg"[2:3]
'c'
>>> "abcdefg"[::2]
'aceg'

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).

Understand?

OTHER TIPS

Try these changes:

print("In Reverse order:")

charSet = ""

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

print(charSet)

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top