Tim
0
Q:

reverse a string or number in python

'String'[::-1] #-> 'gnirtS'
7
'hello world'[::-1]
'dlrow olleh'
20

  txt =  "Hello World" [::-1]

  print(txt) 
5
# 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)
3
#linear

def reverse(s): 
  str = "" 
  for i in s: 
    str = i + str
  return str

#splicing
'hello world'[::-1]

#reversed & join
def reverse(string): 
    string = "".join(reversed(string)) 
    return string
  
 
  
9
# Python string/number reverser
# Kinda too much code, so don't use this, use the other examples under this answer.
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)
-1
text = 'this is a string'
txt = "Hello World"[::-1]
  
 #or 
reversedstring = text[::-1]
print(reversedstring)
print(txt) 
-1

New to Communities?

Join the community