string reversal python code example

Example 1: how to reverse a string in python

# in order to make a string reversed in python 
# you have to use the slicing as following

string = "racecar"
print(string[::-1])

Example 2: how to reverse a string in python

'your sting'[::-1]

Example 3: how to print an input backwards in python

str="Python" # initial string
stringlength=len(str) # calculate length of the list
slicedString=str[stringlength::-1] # slicing 
print (slicedString) # print the reversed string

Example 4: reverse a string or number in python

# Python string/number reverser
example_number = 12143
example_string = "Hello there"

def reverse(thing): 
    thing = str(thing) # convert it to a string, just in case it was a number
    list_of_chars = [char for char in thing]
    reversed_list_of_chars = []
    x = -1
    
    for char in list_of_chars:
      reversed_list_of_chars.append(list_of_chars[x])
      x += -1
    
    reversed_thing = ''.join(reversed_list_of_chars)
    
    return reversed_thing
    # Or alternatively do:
    print(reversed_thing)

# Run it by doing this
reverse(example_number)
reverse(example_string)

Tags:

Misc Example