Question 3.2: Write a Python function named "reverse_string" that takes a string as input and returns the reverse of the input string.
时间: 2024-03-10 08:45:28 浏览: 73
Sure, here's a Python function named "reverse_string" that takes a string as input and returns the reverse of the input string:
```python
def reverse_string(s):
# Use slicing to reverse the string
return s[::-1]
```
This function takes a string `s` as input and returns the reverse of the string using slicing. The `[::-1]` notation is a slice that starts at the end of the string and ends at the beginning of the string, with a step of -1 (i.e., it goes backwards). This effectively reverses the string.
Here's an example of how to use the function:
```python
s = "hello world"
reversed_s = reverse_string(s)
print(reversed_s) # prints "dlrow olleh"
```
In this example, we pass the string "hello world" to the `reverse_string` function and assign the result to the variable `reversed_s`. We then print `reversed_s`, which should be the reverse of the input string.
阅读全文