There’s got to be an easier way of doing this…. I wanted to harden an existing random password generator by insterting a random special character into the middle of the string. Task at hand: split string into two parts, left and right; return a string with the special characters in the middle of the left, right parts.
Here’s what I came up with in PHP:
$str = "somestringofcharacters"; $middle = "^"; $half = (int) ( (strlen($str) / 2) ); // cast to int incase str length is odd $left = substr($str, 0, $half); $right = substr($str, $half); echo $left.$middle.$right;
This is what it would look like in python:
>>> s = "somestringofcharacters" >>> m = "^" >>> s[:len(s)/2] + m + s[len(s)/2:] 'somestringo^fcharacters'