The String class might have some helpful function to do that, did you search the String documentation via Godot? Answer from Deleted User on reddit.com
Top answer
1 of 14
3161

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'

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".

2 of 14
329

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

>>> 'a string'[::-1]
'gnirts a'

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

>>> ''.join(reversed('a string'))
'gnirts a'

or for readability and reusability, put the slice in a function

def reversed_string(a_string):
    return a_string[::-1]

and then:

>>> reversed_string('a_string')
'gnirts_a'

Longer explanation

If you're interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python's str object.

Here is a couple of things about Python's strings you should know:

  1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

  2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

    string[subscript]
    

The subscript creates a slice by including a colon within the braces:

    string[start:stop:step]

To create a slice outside of the braces, you'll need to create a slice object:

    slice_obj = slice(start, stop, step)
    string[slice_obj]

A readable approach:

While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

Most performant approach:

Much faster is using a reverse slice:

'foo'[::-1]

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

def reversed_string(a_string):
    return a_string[::-1]

And usage is simply:

reversed_string('foo')

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265

CPython optimizes string concatenation, whereas other implementations may not:

... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

Discussions

Why does [::1] reverse a string in Python?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
15
12
September 21, 2023
Method for reversing strings - Ideas - Discussions on Python.org
There may be other methods like splitting the string, reversing the resulting list, and then joining it back, but that’s a bit of work! There have been several times in my QA career where I am scripting in Python and need to reverse a string, but I have to look up the [::-1] syntax because ... More on discuss.python.org
🌐 discuss.python.org
1
February 20, 2025
How to reverse a string in c without using strrev?
You have string[begin] = '\0' where it should be output[begin] = '\0' More on reddit.com
🌐 r/C_Programming
8
1
September 9, 2019
How to reverse a string? - Databases - SitePoint Forums | Web Development & Design Community
Take a string like +54321, how to reverse it to +12345? In Bash: echo +54321 | rev 12345+ rev is not self explanatory. How would you suggest to do that in a self explanatory way but with the least amount of code? I was thinking about C, Python, Perl, Java and C#, but I never worked with any ... More on sitepoint.com
🌐 sitepoint.com
0
January 3, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › java › reverse-a-string-in-java
Reverse a String in Java - GeeksforGeeks
Explanation: Characters are stored in a list and reversed using Collections.reverse(). This approach is helpful when you’re already working with Java collections. StringBuffer is similar to StringBuilder but thread-safe.
Published   October 14, 2025
🌐
Online String Tools
onlinestringtools.com › reverse-string
Reverse a String – Online String Tools
Simple, free and easy to use online tool that reverses strings. No intrusive ads, popups or nonsense, just a string reverser. Load a string and reverse it.
🌐
Reddit
reddit.com › r/learnprogramming › why does [::1] reverse a string in python?
r/learnprogramming on Reddit: Why does [::1] reverse a string in Python?
September 21, 2023 -

For example:

txt = "Hello World"[::-1]

Isn't the splice syntax [start : stop: step]? And default of start and stop are the beginning and end of the string? So that would make the above start at the beginning, stop at the end, but step by -1. That feels like it would start at the beginning, then step backwards to...before the beginning of the string?

Sorry for the silly question, I just can't figure out why this syntax works the way it does.

🌐
Python.org
discuss.python.org › ideas
Method for reversing strings - Ideas - Discussions on Python.org
February 20, 2025 - There may be other methods like splitting the string, reversing the resulting list, and then joining it back, but that’s a bit of work! There have been several times in my QA career where I am scripting in Python and need to reverse a string, but I have to look up the [::-1] syntax because ...
Find elsewhere
🌐
Interviewing.io
interviewing.io › questions › reverse-string
How to Reverse a String [Interview Question + Solution]
September 13, 2018 - We can loop through each character of the original string and build the reversed string iteratively. We start with an empty string and append the characters to it as we loop across the original string. Please note that we are appending the characters to the beginning of the string.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string
Reverse a String – Complete Tutorial - GeeksforGeeks
After each swap, increment the left pointer and decrement the right pointer to move towards the center of the string. This will swap all the characters in the first half with their corresponding character in the second half. ... // C++ program to reverse a string using two pointers #include <iostream> using namespace std; string reverseString(string &s) { int left = 0, right = s.length() - 1; // Swap characters from both ends till we reach // the middle of the string while (left < right) { swap(s[left], s[right]); left++; right--; } return s; } int main() { string s = "abdcfe"; cout << reverseString(s); return 0; }
Published   October 3, 2025
🌐
Reddit
reddit.com › r/c_programming › how to reverse a string in c without using strrev?
r/C_Programming on Reddit: How to reverse a string in c without using strrev?
September 9, 2019 -

So I have a task which requires me to manipulate arrays and reverse a string. I have written the code but it doesn't work quite perfectly. The problem is that it reverses the string BUT it also includes weird symbols after the reversed string. I'm pretty new to programming and I have tried to find an answer elsewhere but don't know what to look for exactly. I appreciate any constructive feedback, Thanks!

#include <stdio.h>

int main(){

char string[256];
char output[256];
int begin;int end;
int count = 0;

printf("Input a string\n");
fgets(string, 256, stdin);

while (string[count] != '\0'){
count++;

end = count - 1;
}
for (begin = 0; begin < count; begin++) {
output[begin] = string[end];
end--;
}
string[begin] = '\0';

printf("%s\n", output);
}
🌐
LeetCode
leetcode.com › problems › reverse-string
Reverse String - LeetCode
The input string is given as an array of characters s. You must do this by modifying the input array in-place [https://en.wikipedia.org/wiki/In-place_algorithm] with O(1) extra memory.
🌐
SitePoint
sitepoint.com › databases
How to reverse a string? - Databases - SitePoint Forums | Web Development & Design Community
January 3, 2024 - MariaDB/MySQL (4.0+) has a REVERSE() function, as does SQL Server (2008+), PHP has strrev, which admittedly is not as clear of a name, C# you’d need to make an array out of the string to use the Array.reverse function, Python doesnt really have a string reversing function, but can reference the string as an array of characters, so you can use the odd looking construction "Hello World"[::-1] to walk backwards through the array…
🌐
GeeksforGeeks
geeksforgeeks.org › problems › reverse-a-string › 1
Reverse a String | Practice | GeeksforGeeks
You are given a string s, and your task is to reverse the string. Examples: Input: s = "Geeks" Output: "skeeG" Input: s = "for" Output: "rof" Input: s = "a" Output: "a" Constraints:1
🌐
Reddit
reddit.com › r/powershell › reverse string of characters
r/PowerShell on Reddit: Reverse String of Characters
June 28, 2022 -

Using PowerShell I need to reverse a string that is 38 characters long, but I need to reverse the string - 2 characters at a time and keep the order such as...

change this “12345678” to this “78563412”

Not exactly sure how to do that with PowerShell.

Just using 12345678 as an example.

Thanks!

--------------------------------------

Script here:

$a = “12345678”

$b = $a.ToCharArray()

$b

Write-Host "`n"

[array]::Reverse($b)

$b

🌐
LeetCode
leetcode.com › problems › reverse-words-in-a-string
Reverse Words in a String - LeetCode
Can you solve this real interview question? Reverse Words in a String - Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters.
🌐
UiPath Community
forum.uipath.com › learning hub
Reverse a string without using reverse() - Learning Hub - UiPath Community Forum
April 30, 2020 - Hi guys. I want to reverse a string without using a reverse function. We can convert the string into CharArray but what should we do post that? Thanks for the help in advance.
🌐
Quora
quora.com › How-do-you-reverse-a-string
How to reverse a string - Quora
Answer (1 of 3): You can reverse a string by lifting one end, then moving it past the other end. It will be completely reversed. If you’re asking about programming, you could use an index starting at zero, swap the character at that index ...
🌐
Rust Programming Language
users.rust-lang.org › help
How to reverse output all characters of a String type? - help - The Rust Programming Language Forum
May 28, 2019 - Hullo, folks. I want to output the reverse of a String value. Like, the reverse of "Hello, world!” is "!dlrow,olleH" is what I want. Here is the code: fn main() { let s1 = String::from("Hello, world!"); let (s1, s2) = reverse_string(s1); println!("The reverse of \"{}\" is \"{}\".", s1, s2); } fn reverse_string(s: String) -> (String, String) { let length = s.len(); let reversed_s: String; for number in (0..length).rev() { reversed_s.push_str(s[number]); } ...
🌐
Spiceworks
community.spiceworks.com › hardware & infrastructure › storage & san
Reverse of a String - Storage & SAN - Spiceworks Community
April 13, 2012 - Hi i have a requirement of reversing a string column in my data. for example if my data is 101,krishna 102,surya 103,asha I want output as 101,anhsirk 102,ayrus 103,ahsa I tried the below logic but it still throwing an error. Plz correct my with my code /Reformat operation/ out::reformat(in) = begin let string(10) str = in.ename; let string(10) z; let string(10) ch; let int a; let decimal(10) l = string_length(in.ename); let int i =0; a=l; for(i,i
🌐
CodeChef
codechef.com › practice › course › strings › STRINGS › problems › PALINDRCHECK
Reverse Words in a String Practice Problem in Strings
Test your knowledge with our Reverse Words in a String practice problem. Dive into the world of strings challenges at CodeChef.