Some more interesting stuff in Python(part-2)

Jyothi
May 10, 2024

--

String reversal

You cannot follow C language method of string reversal in Python :) . Below code throws an error:

Above code segment is trying to modify the string in place. In Python, strings are immutable, and cannot change individual characters directly. New memory is a must here. The advantage is the same variable can be used for multiple data types. Python provides different options to reverse the string:

  • Convert the string to list and use the above-mentioned method, then join the list using ‘’.join(s)
  • using reversed function: ‘’.join(reversed(s))
  • take each char and add to new variable:
  • read from the end: s[::-1]

--

--