Skip to content
The Chat Archive
claude-2.0· Anthropic Arena Human Preference 55K

Write a code to reverse a string in python

  1. User

    Write a code to reverse a string in python

  2. Assistant

    Here is a simple Python code to reverse a string:

    def reverse_string(input_str):
        reversed_str = ""
        index = len(input_str)
        while index > 0:
            reversed_str += input_str[ index - 1 ]
            index = index - 1
        return reversed_str
    
    input_str = "Hello World"
    print("Original String: ", input_str)
    print("Reversed String: ", reverse_string(input_str))
    

    The key steps are:

    1. Initialize an empty string reversed_str to store the reversed string

    2. Get the index of the last character of the input string

    3. Loop through the input string from the last index to 0

    4. For each character, add it to the reversed_str

    5. Return the reversed_str

    This code traverses the input string in reverse order and appends each character to a new string to construct the reversed string.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.