gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Untitled conversation
- User
[22:47]pkr: How do you reverse a string?
- Assistant
There are a few ways to reverse a string:
- Using a loop: Iterate through the string in reverse order and build a new string by appending each character to it. Here's an example in Python:
pythondef reverse_string(string): reversed_str = "" for i in range(len(string)-1, -1, -1): reversed_str += string[i] return reversed_str string = "Hello World!" print(reverse_string(string))Output:
code!dlroW olleH- Using string slicing: In languages like Python, you can also reverse a string using string slicing. Here's an example:
pythondef reverse_string(string): return string[::-1] string = "Hello World!" print(reverse_string(string))