PYTHON substr_replace

is this article helpful?
Python replacement for PHP's substr_replace [ edit | history ]
Try this one without any warranty for validity:

def substr_replace(subject,replace,start,length):
	if length == None:
		return subject[:start] + replace
	elif length < 0:
		return subject[:start] + replace + subject[length:]
		return subject[:start] + replace + subject[start+length:]

PHP substr_replace

PHP original manual for substr_replace [ show | ]


(PHP 4, PHP 5)

substr_replaceReplace text within a portion of a string


mixed substr_replace ( mixed $string , string $replacement , int $start [, int $length ] )

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement .



The input string.


The replacement string.


If start is positive, the replacing will begin at the start 'th offset into string .

If start is negative, the replacing will begin at the start 'th character from the end of string .


If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string . Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Return Values

The result string is returned. If string is an array then array is returned.


Example #1 substr_replace() example

"Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var'bob'0) . "<br />\n";
substr_replace($var'bob'0strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var'bob'00) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var'bob'10, -1) . "<br />\n";
substr_replace($var'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var''10, -1) . "<br />\n";


Note: This function is binary-safe.

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • substr() - Return part of a string