DEV Community 👩‍💻👨‍💻

HHMathewChan
HHMathewChan

Posted on • Updated on

Python daily exercise 3: reverse a string

Question

  • write a program to reverse a given string
str1 = "PYnative"

Enter fullscreen mode Exit fullscreen mode
  • Expected output
evitanYP
Enter fullscreen mode Exit fullscreen mode

My attempt

str1 = "PYnative"
reversed_string = str1[::-1]
print(reversed_string)
Enter fullscreen mode Exit fullscreen mode

Recommend solution

str1 = "PYnative"
print("Original String is:", str1)

str1 = ''.join(reversed(str1))
print("Reversed String is:", str1)
Enter fullscreen mode Exit fullscreen mode

My reflection

I only know how to reversed a string using string slicing method, but do not know the reverse() and the join().

Top comments (2)

Collapse
 
jmagave profile image
jmagave

Looks like using slice is 4x faster. Timed with %timeit command of YPython.

%timeit s[::-1]
81 ns ± 1.05 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit "".join(reversed(s))
311 ns ± 2.89 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mathewchan profile image
HHMathewChan Author

just find out your comment, good to know how to count program time, thx

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.