SoftwareSideHustles
How-To

How to Reverse a String in Python, JavaScript, Java, C# and Go (Including Emoji)

One-liners for reversing a string in the major languages, the interview-style manual approach, and why most of them break on emoji and accented characters — with fixes.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: Python s[::-1], JavaScript [...s].reverse().join(""), Java new StringBuilder(s).reverse().toString(), C# new string(s.Reverse().ToArray()). Those work for plain text. If your strings can contain emoji, flags or combining accents, read the Unicode section — most one-liners quietly corrupt them.

Reverse a string: one-liners by language

LanguageReverseHandles emoji?
Pythons[::-1]Single code points yes; multi-part emoji no
JavaScript[...s].reverse().join("")Surrogate pairs yes; multi-part emoji no
JavaScript (naive)s.split("").reverse().join("")No — breaks every emoji
Javanew StringBuilder(s).reverse().toString()Surrogate pairs yes; multi-part emoji no
C#new string(s.Reverse().ToArray())No — breaks surrogate pairs
Goreverse a []runeCode points yes; multi-part emoji no

How do I reverse a string in Python?

python
s = "hello"
print(s[::-1]) # 'olleh'
print("".join(reversed(s))) # 'olleh'

s[::-1] is a slice with a step of -1: start at the end and walk backwards. Strings are immutable, so both forms build a new string in O(n) time. reversed(s) returns an iterator, which is why it needs "".join(...) — calling str(reversed(s)) gives you '<reversed object at 0x...>', a common surprise.

How do I reverse a string in JavaScript?

javascript
const s = "hello";
[...s].reverse().join(""); // "olleh"
Array.from(s).reverse().join(""); // "olleh"

Strings have no reverse() method, so you convert to an array, reverse it and join. Prefer the spread form over s.split(""). JavaScript strings are UTF-16, and split("") splits code units, tearing emoji such as 😀 (two code units) into invalid halves:

javascript
"ab😀".split("").reverse().join(""); // "\uDE00\uD83Dba" — broken
[..."ab😀"].reverse().join(""); // "😀ba" — correct

The spread operator iterates by code point, which keeps surrogate pairs together.

How do I reverse a string in Java?

java
String reversed = new StringBuilder("hello").reverse().toString(); // "olleh"

StringBuilder.reverse() is documented to treat surrogate pairs as single units, so basic emoji survive. Avoid concatenating in a loop (result = c + result) — each concatenation copies the string, which turns an O(n) task into O(n²).

How do I reverse a string in C# and Go?

csharp
string reversed = new string("hello".Reverse().ToArray()); // "olleh"
// or, without LINQ:
char[] chars = "hello".ToCharArray();
Array.Reverse(chars);
string r = new string(chars);

Both reverse UTF-16 chars, so they break emoji. For user-facing text, use StringInfo to iterate text elements (graphemes) instead.

Go strings are byte sequences, so reversing bytes destroys any multi-byte UTF-8 character. Convert to runes first:

go
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}

The manual approach (what interviewers want)

When the point is to show you understand the algorithm, use two pointers that swap from both ends towards the middle:

python
def reverse(s: str) -> str:
chars = list(s)
i, j = 0, len(chars) - 1
while i < j:
chars[i], chars[j] = chars[j], chars[i]
i += 1
j -= 1
return "".join(chars)

It runs in O(n) time and, on a mutable array, O(1) extra space. Mention the edge cases unprompted: the empty string, a single character, and even versus odd lengths (the i < j condition handles all three).

Why reversing breaks emoji and accents

What a person sees as one character — a grapheme — can be several code points:

  • é may be e followed by a combining acute accent (U+0301). Reverse it and the accent lands on the wrong letter.
  • 👍🏽 is a thumbs-up plus a skin-tone modifier.
  • 👨‍👩‍👧 is three people joined by zero-width joiners.
  • 🇬🇧 is two regional-indicator letters; reversed, it becomes a different flag.

Every one-liner above reverses code points or code units, not graphemes. When the output is shown to humans, segment by grapheme first:

javascript
const seg = new Intl.Segmenter(undefined, { granularity: "grapheme" });
const reverseText = (s) => [...seg.segment(s)].map((x) => x.segment).reverse().join("");
reverseText("ab👍🏽"); // "👍🏽ba"

In Python, the third-party regex module matches graphemes with \X: "".join(reversed(regex.findall(r"\X", s))).

Checking for a palindrome

A palindrome check is "reverse and compare", usually after normalising:

python
import re
def is_palindrome(s: str) -> bool:
cleaned = re.sub(r"[^a-z0-9]", "", s.lower())
return cleaned == cleaned[::-1]
is_palindrome("A man, a plan, a canal: Panama") # True

A two-pointer version avoids building the reversed copy and can stop at the first mismatch, which matters for very long strings.

Frequently asked questions

What is the fastest way to reverse a string in Python?

s[::-1]. It runs in C and is faster than "".join(reversed(s)) or a manual loop. All are O(n).

Why doesn't JavaScript have a string reverse method?

Because "reverse" is ambiguous for Unicode text — code units, code points or graphemes give different answers. Convert to an array with the granularity you need, then reverse.

Can I reverse a string in place?

Not in Python, JavaScript, Java or C#, where strings are immutable. You reverse a mutable copy (a list, array or StringBuilder) and build a new string. In C and C++ you can reverse a char buffer in place with std::reverse.

How do I reverse the words in a sentence instead of the characters?

Split on whitespace, reverse the list, join: " ".join(s.split()[::-1]) in Python or s.split(" ").reverse().join(" ") in JavaScript. See how to split a string for whitespace gotchas.

Where this skill pays off

"Reverse a string" looks trivial, which is exactly why AI models get it subtly wrong — split("") on emoji, quadratic concatenation, missing edge cases. Developers who can explain why one version is better than another get paid to evaluate AI coding responses. Try a real example in our free code comparison lab, or read what makes one coding solution better than another.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy