fruit = 'banana' index = 0 while index < len(fruit): letter = fruit[index] print(letter, end='') index = index + 1I tried to reverse the string by changing 3rd line to
letter = fruit[-index]
, but it didn't work
print string in reverse
|
fruit = 'banana' index = 0 while index < len(fruit): letter = fruit[index] print(letter, end='') index = index + 1I tried to reverse the string by changing 3rd line to letter = fruit[-index] , but it didn't work
Oct-02-2018, 11:49 PM
>>> s = 'Welcome to the forum!' >>> s[::-1] '!murof eht ot emocleW' >>>This is called slicing. The format is [start_index, stop_index, step]. Stop_index is exclusive. In this case, the start and the stop are missing which means we get the whole string. And since the step is negative it counts backward.
Oct-03-2018, 12:42 AM
(Oct-02-2018, 11:49 PM)wavic Wrote:>>> s = 'Welcome to the forum!' >>> s[::-1] '!murof eht ot emocleW' >>>This is called slicing. The format is [start_index, stop_index, step]. Stop_index is exclusive. In this case, the start and the stop are missing which means we get the whole string. And since the step is negative it counts backward. thanks for the reply and the welcome . but slicing is explained after the exercise. so i solved it like this instead. fruit = 'banana' index = len(fruit) - 1 while index >= 0: letter = fruit[index] print(letter, end='') index = index - 1
Oct-04-2018, 04:23 PM
This would have been simpler if you can't use slicing yet:
fruit = 'banana' reverse = '' for letter in fruit: reverse = letter + reverse print(reverse)We generally avoid directly indexing into lists/strings/etc if we don't need to.
I am trying to help you, really, even if it doesn't always seem that way
Oct-04-2018, 06:55 PM
(Oct-04-2018, 04:23 PM)gruntfutuk Wrote: This would have been simpler if you can't use slicing yet: I don't get it. shouldn't that just go through each letter and print the result. why did it do it in reverse?
Oct-04-2018, 08:11 PM
(Oct-04-2018, 06:55 PM)pseudo Wrote: why did it do it in reverse?because each letter is added at the begining of the result. to see it fruit = 'banana' reverse = '' for letter in fruit: reverse = letter + reverse print(reverse)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link Create MCV example Debug small programs |
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Reading a text until matched string and print it as a single line | cananb | 1 | 2,043 |
Nov-29-2020, 01:38 PM Last Post: DPaul |
|
How to print the docstring(documentation string) of the input function ? | Kishore_Bill | 1 | 3,568 |
Feb-27-2020, 09:22 AM Last Post: buran |
|
Reverse string sentence with for loop? | BillGates | 3 | 6,129 |
May-02-2017, 04:15 PM Last Post: wavic |
|
Print the index of the vowels in a string | MeeranRizvi | 4 | 14,742 |
Dec-29-2016, 02:43 PM Last Post: snippsat |