Welcome, guest | Sign In | My Account | Store | Cart

You want to replace that portion of a string at a given position.

Python, 6 lines
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]

# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]

Python strings are immutable, so it is not possible to modify the original string directly. Instead a new string is constructed by extracting those parts of the original string that appear before and after the substring that is to be replaced, and concatenating those slices with the replacement substring. This new string can then be assigned to the original variable.

As an alternative to specifying the substring by position, you may want to specify the text to be looked for instead, using the replace() method on the original string; or, more powerfully, you could use the sub() function from the 're' module to specify a regular expression for the looked-for text.

Created by Hamish Lawson on Mon, 4 Jun 2001 (PSF)
Python recipes (4591)
Hamish Lawson's recipes (6)

Required Modules

  • (none specified)

Other Information and Tasks