-9

I am learning Python and want to reverse a string.

Example:

Input: hello

Output: olleh

I know slicing works (s[::-1]) but I want to know if there are other Pythonic or recommended ways to do it. Is there a difference in performance or readability between the methods?

New contributor
Ronit Raj Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

1 Answer 1

-5
You can reverse a string in Python in multiple ways:

1. Using slicing (shortest and fastest)
s = "hello"
print(s[::-1])

2. Using reversed() with join
s = "hello"
print("".join(reversed(s)))

3. Using a loop
s = "hello"
res = ""
for ch in s:
    res = ch + res
print(res)

All of these output: "olleh"
New contributor
Ronit Raj Verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.