# Slice notation takes the form [start:stop:step]. In this case,
# we omit the start and stop positions since we want the whole string.
# We also use step = -1, which means, "repeatedly step from right to left by
# 1 character".
'hello world'[::-1]
# result: 'dlrow olleh'
# Function to reverse a string
def reverse(string):
string = string[::-1]
return string
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using extended slice syntax) is : ", end="")
print(reverse(s))
# To reverse a list use simply: reverse() method
# Example
list = [1, 2, 3]
list.reverse()
# Output
[3, 2, 1]
# to reverse any other type, we can use reversed()
# The reversed() function returns an iterator that accesses the given sequence in the reverse order.
# Example
list = [1, 2, 3]
list(reversed(list))
# Output
[3, 2, 1]
# reversed() returns an iterator so we can loop other it
# Example
for num in reversed(list):
print(num)
# Output
3
2
1
# Python code to reverse a string
# using loop
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "HelloWorld"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
s = "SoftHunt" # initial string
reversedString=[ ]
index = len(s) # calculate length of string and save in index
while index > 0:
reversedString += s[ index - 1 ] # save the value of str[index-1] in reverseString
index = index - 1 # decrement index
print(reversedString) # reversed string