# StringReverse.py (c) Kari Laitinen # http://www.naturalprogramming.com # 2006-03-02 File created. # 2022-12-16 Converted to Python 3. # String literals can be written both with single quotes # and with double quotes. # Python does not have type char, but single-character # strings can be considered characters. print( "\n This program is able to reverse a string." \ "\n Please, type in a string.\n\n ", end="" ) string_from_keyboard = input() print( "\n String length is %d." % len( string_from_keyboard ) ) print( "\n\n String in reverse character order: \n ", end="" ) character_index = len( string_from_keyboard ) while character_index > 0 : character_index = character_index - 1 print( string_from_keyboard[ character_index ], end=" " ) # The following loop uses special string indexing techniques of # Python. The index of last character is -1, the index of # penultimate character is -2, etc. print( "\n\n Again in reverse character order: \n " , end="" ) character_index = 0 while character_index > - len( string_from_keyboard ) : character_index = character_index - 1 print( string_from_keyboard[ character_index ], end=" " ) # In order to show the reversed string without spaces, one # possibility is to do the following: character_index = len( string_from_keyboard ) reversed_string = "" while character_index > 0 : character_index = character_index - 1 reversed_string += string_from_keyboard[ character_index ] print( "\n\n Reversed without spaces: \n " + reversed_string, end="" ) # Yet another possibility is to convert the string to a list of characters, # reverse the list, and then convert the list to a string: given_string_as_list = list( string_from_keyboard ) given_string_as_list.reverse() reversed_string = "".join( given_string_as_list ) print( "\n\n Reversed as list: \n " + reversed_string )