Reversing Strings in Python and PowerShell

By: Cam Wohlfeil
Published: 2018-07-09 0000 EDT
Category: Programming
Tags: python, powershell

Reversing a string is super easy in Python and a little more complicated in PowerShell. Both of them have multiple ways to do it, all basically similar. The only trade-offs appear to be obvious: do you care about the overhead of a function call, line count, verbosity, etc. Personally, I'd use the first PowerShell method in a script or module I plan to maintain or share and the second method in one-liners or temporary scripts.

$a = "abcde"
$b = $a.ToCharArray()
[array]::Reverse($b)
$c = -join($b)

# Or

"PowerShell" | %{ -join $_[$_.Length..0] }

My choice for the Python methods is basically the same, I'd prefer the function when writing maintainable code and the simple string slice when writing one-offs. I'm never a fan of using "".join().

# Basic Function w/ string splicing
def reverse(s):
if len(s) == 0:
    return s
else:
    return reverse(s[1:]) + s[0]

# Slice
string[::-1]

# Reversed iterator function and join
"".join(reversed(string))