Reputation: 460
I would like to get input from a user and then to print the string reversed like this:
input:
hello
output:
o
ol
oll
olle
olleh
This is my code:
s = input()
for i in range(len(s) - 2, -1, -1):
print(s[:i:-1])
And output i receive is:
o
ol
oll
olle
I am constantly missing the last character. I tried many variations of the slicing. What am I missing?
Upvotes: 3
Views: 341
Reputation: 30971
The very basic method to reverse a string s
is s[::-1]
(and save it
in another variable, say s2
).
Then, to print consecutive rows with increasing part of this string (s2
),
you need a loop over range(1, len(s2)+1)
, stating the upper limit of s2
(excluding).
So the script can look like below:
s = 'hello'
s2 = s[::-1]
for i in range(1, len(s2)+1):
print(s2[:i])
Upvotes: 0
Reputation: 51623
You could also simply reverse the complete thing and print it sliced from the start to save you some headache:
b = "hello" # your input
h = b[::-1] # inverse all - so this is now olleh
# list slicing is from:exclusive to - so simply add 1 to fit with the ranges values 0-4
for k in ( h[0:i+1] for i in range(0,len(h)) ):
print(k)
Output:
o
ol
oll
olle
olleh
Upvotes: 0
Reputation: 1
I would do it this way:
a = "Hello"
for i in range(len(a)):
print(a[-i-1])
This way you are not dealing with string slices, only indexing the string and there isn't a bunch of extra numbers to figure out what they are doing.
Upvotes: 0
Reputation: 164613
Easiest perhaps is to iterate from -1
backwards:
s = 'hello'
for i in range(1, len(s)+1):
print(s[-1: -i-1: -1])
hello
o
ol
oll
olle
olleh
The way this works, you are slicing sequentially:
s[-1: -2: -1]
,s[-1: -3: -1]
,...s[-1: -len(s)-1: -1]
Upvotes: 2
Reputation: 136
To get the full string reversed you must use s[::-1]
omitting the first value.
Since that doesn't fit into your iteration you'll have to use something like:
s = input()
for i in range(len(s) - 2, -1, -1):
print(s[:i:-1])
print(s[::-1])
Upvotes: 2
Reputation: 243877
You must first obtain the substring and then reverse it:
s = "hello"
for i in range(len(s)-1, -1, -1):
print(s[i:][::-1])
Or:
s = "hello"
for i, _ in enumerate(s):
print(s[i:][::-1])
Or reverse the word and get the substring:
s = "hello"
for i, _ in enumerate(s):
print(s[::-1][:i+1])
Upvotes: 4