w3resource

Python: Reverse a string


Reverse a string.

Write a Python program to reverse a string.

Python String Exercises: Reverse a string

Sample Solution:

Python Code:

# Define a function 'reverse_string' that takes a string 'str1' as input.
# The function returns the reversed version of the input string.
def reverse_string(str1):
    return ''.join(reversed(str1))

# Print an empty line for spacing.
print()

# Call the 'reverse_string' function with the input "abcdef", reverse the string, and print the result.
print(reverse_string("abcdef"))

# Call the 'reverse_string' function with the input "Python Exercises.", reverse the string, and print the result.
print(reverse_string("Python Exercises."))

# Print an empty line for spacing.
print() 

Sample Output:

fedcba                                                                                                        
.sesicrexE nohtyP 

Flowchart:

Flowchart: Reverse a string

Python Code Editor:

Previous: Write a Python program to count occurrences of a substring in a string.
Next: Write a Python program to reverse words in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.