{"id":4941,"date":"2026-09-30T17:05:07","date_gmt":"2026-09-30T17:05:07","guid":{"rendered":"https:\/\/www.askpython.com\/?p=4941"},"modified":"2026-09-30T17:05:07","modified_gmt":"2026-09-30T17:05:07","slug":"python-replace-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/string\/python-replace-function","title":{"rendered":"Python replace() function"},"content":{"rendered":"<!-- article-type: how-to-use -->\n<!-- receipt-backed-first-person -->\n\n<p class=\"wp-block-paragraph\">Calling `&#8221;Python python PYTHON&#8221;.replace(&#8220;python&#8221;, &#8220;Ruby&#8221;)` changes only the lowercase match. I appreciate the `count` argument because it caps how many matches change.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Pass the old and new text to `str.replace()` and check the returned string. Compare that returned string with the original to see which text changed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What str.replace() changes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">str.replace(old, new, count=-1) searches a string for an exact substring and <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#str.replace\" target=\"_blank\" rel=\"noopener\">returns a copy<\/a> with matching occurrences replaced.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default, it changes every match. Set count to limit the number of replacements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Assign the returned string when later code needs the changed text, because the source string stays unchanged.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython3 -c &#039;text = &quot;ref-17, ref-28&quot;; result = text.replace(&quot;ref-&quot;, &quot;INV-&quot;); print(result); print(text)&#039; \n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"420\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic.png\" alt=\"Terminal output showing Python replace() returning a changed string and leaving the source unchanged\" class=\"wp-image-71632\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic-300x66.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic-1024x224.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic-768x168.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-basic-1536x336.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>The replacement result is printed first, followed by the unchanged source string.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Python strings are immutable, so replace() returns a result instead of changing the original string. Assign that result back to the same name if later code should use the changed text.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What you need before replacing text<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Call replace() on the string that contains the text you want to change, then pass the exact substring and its replacement.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Argument<\/th><th>What it supplies<\/th><\/tr><\/thead><tbody><tr><td>old<\/td><td>The literal substring to find<\/td><\/tr><tr><td>new<\/td><td>The text inserted for each match<\/td><\/tr><tr><td>count<\/td><td>An optional limit, defaulting to every match<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Matching is case-sensitive and literal. Python&#8217;s <a href=\"https:\/\/docs.python.org\/3\/library\/re.html#re.sub\" target=\"_blank\" rel=\"noopener\">re.sub()<\/a> handles regular-expression matching and can ignore case with re.IGNORECASE.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Use replace() for exact text changes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Choose the example by the object you have and how many matches you want to change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Replace every exact match<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The method replaces each non-overlapping match, and the replacement can have a different length from the text it finds.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntext = &quot;Py and Py&quot;\nprint(text.replace(&quot;Py&quot;, &quot;Python&quot;))\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Both matches become Python, and the replacement&#8217;s greater length does not change the method&#8217;s search. The original variable still refers to the unchanged string.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Limit how many matches change<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Count limits the number of matches, so I saw the final warn stay unchanged after the first two replacements. A zero count changes none, and -1 keeps the all-matches default.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython3 -c &#039;print(&quot;warn: warn: warn&quot;.replace(&quot;warn&quot;, &quot;hold&quot;, 2))&#039;\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"358\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count.png\" alt=\"Terminal output showing str.replace with count 2 leaves the third warn occurrence unchanged\" class=\"wp-image-71633\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count-300x56.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count-1024x191.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count-768x143.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-count-1536x286.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>count=2 changes the first two matches and leaves the last warn in place.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Match capitalization or a regular expression<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">str.replace() matches exact capitalization, so re.sub() fits when a regular expression must ignore case.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport re\n\ntext = &quot;Python python PYTHON&quot;\nprint(text.replace(&quot;python&quot;, &quot;Ruby&quot;))\nprint(re.sub(&quot;python&quot;, &quot;Ruby&quot;, text, flags=re.IGNORECASE))\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The literal call changes lowercase python only, and re.IGNORECASE makes re.sub() match each capitalization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Replace text inside a list<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A list has no string replace() method, so call the method on each string element and collect the results. A list comprehension creates a new list while leaving the input list intact.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nwords = &#x5B;&quot;red cat&quot;, &quot;blue cat&quot;]\nupdated = &#x5B;word.replace(&quot;cat&quot;, &quot;dog&quot;) for word in words]\nprint(words)\nprint(updated)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">For a list of numbers, use a list comprehension that compares each value with the target number.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Chain replacements in order<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each call receives the previous result, so a later replacement can change text inserted by an earlier call.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython3 -c &#039;print(&quot;cat&quot;.replace(&quot;cat&quot;, &quot;dog&quot;).replace(&quot;dog&quot;, &quot;fox&quot;))&#039;\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"358\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain.png\" alt=\"Terminal output fox after chained replace calls change cat to dog and then dog to fox\" class=\"wp-image-71637\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain-300x56.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain-1024x191.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain-768x143.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-chain-1536x286.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>The second replace call receives the first call\u2019s result and changes dog to fox.<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Use replace() on a pandas column<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A pandas Series is a one-dimensional labeled sequence, often a DataFrame column. Its str accessor applies a string operation to each value that supports it, and leaves missing values unchanged.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The pandas accessor accepts case and regex controls. str.replace() takes an optional count argument.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If uv is installed, this command supplies pandas for one run and performs a case-insensitive literal replacement.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nuv run --with pandas python -c &#039;import pandas as pd; s = pd.Series(&#x5B;&quot;Python&quot;, &quot;python&quot;, &quot;PYTHON&quot;, &quot;JavaScript&quot;]); print(s.str.replace(&quot;python&quot;, &quot;Ruby&quot;, case=False, regex=False).to_list())&#039;\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"482\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace.png\" alt=\"Pandas Series.str.replace performs a case-insensitive literal replacement and leaves JavaScript unchanged\" class=\"wp-image-71634\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace-300x75.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace-1024x257.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace-768x193.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/pandas-replace-1536x386.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>Series.str.replace with case=False and regex=False replaces the Python variants but leaves JavaScript unchanged.<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Call<\/th><th>What it changes<\/th><th>Useful option<\/th><\/tr><\/thead><tbody><tr><td>str.replace()<\/td><td>Substrings in one Python string<\/td><td>count limits matches<\/td><\/tr><tr><td>Series.str.replace()<\/td><td>Matching text in each Series value<\/td><td>case and regex control matching<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">case=False matches each capitalization of Python. regex=False keeps the search literal, so JavaScript stays unchanged.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Where str.replace() stops<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The edge cases come from what counts as a match and which object owns the method. An empty old value behaves differently from an empty replacement.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If old does not occur, the text stays unchanged.<\/li>\n\n<li>An empty new value removes each matching substring.<\/li>\n\n<li>An empty old value is inserted at both ends and between each character.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">I got &#8220;ba&#8221; when I replaced &#8220;aa&#8221; with &#8220;b&#8221; in &#8220;aaa&#8221;. The second candidate overlaps a character already used by the first match.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython3 -c &#039;print(&quot;aaa&quot;.replace(&quot;aa&quot;, &quot;b&quot;))&#039;\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"296\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap.png\" alt=\"Terminal output ba from replacing aa in aaa, showing overlapping matches are not reused\" class=\"wp-image-71635\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap-300x46.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap-1024x158.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap-768x118.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-overlap-1536x237.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>The first aa match is replaced, so the overlapping second start is skipped and ba remains.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Use a regular expression with lookahead when overlapping matches matter, and use Python&#8217;s <a href=\"https:\/\/www.askpython.com\/python\/string\/python-string-find\">string find() method<\/a> when you need a substring&#8217;s position.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choose a method by the match you need<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">str.translate() applies a mapping to each character in the original text, so output from one mapping cannot become input to the next. Use it when several one-character substitutions act on one string.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\npython3 -c &#039;text = &quot;one-two_three&quot;; table = str.maketrans({&quot;-&quot;: &quot; &quot;, &quot;_&quot;: &quot; &quot;}); print(text.translate(table))&#039;\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"420\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate.png\" alt=\"Terminal output one two three after str.translate replaces hyphens and underscores with spaces\" class=\"wp-image-71636\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate.png 1920w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate-300x66.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate-1024x224.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate-768x168.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2026\/09\/replace-translate-1536x336.png 1536w\" sizes=\"auto, (max-width: 1920px) 100vw, 1920px\" \/><figcaption>str.translate applies both character mappings to the original text in one pass.<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1790722213494\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Is str.replace() deprecated in Python 3?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No. The current Python documentation includes str.replace() in the built-in string API. Call it on a string and use the returned string.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1790722213495\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How do I replace only the first occurrence?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Pass count=1, then use the returned string to keep the first replacement.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1790722213496\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How do I replace an integer in a list?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Use a list comprehension that substitutes the target number and carries other values forward. str.replace() operates on text inside a string.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Calling `&#8221;Python python PYTHON&#8221;.replace(&#8220;python&#8221;, &#8220;Ruby&#8221;)` changes only the lowercase match. I appreciate the `count` argument because it caps how many matches change. Pass the old and new text to `str.replace()` and check the returned string. Compare that returned string with the original to see which text changed. What str.replace() changes str.replace(old, new, count=-1) searches a [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":71638,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-4941","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-string"],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4941","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=4941"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/4941\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/71638"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=4941"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=4941"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=4941"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}