๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-program-to-replace-every-nth-character-in-string
Python program to replace every Nth character in String | GeeksforGeeks
April 25, 2023 - In this, we perform an iteration of each character and check if its Nth by performing modulo, i.e finding remainder by N. If its Nth occurrence, the character is replaced by K. ... # initializing string test_str = "geeksforgeeks is best for ...
๐ŸŒ
DEV Community
dev.to โ€บ fedingo โ€บ how-to-replace-character-at-nth-index-in-python-string-1b7p
How to Replace Character at Nth Index in Python String - DEV Community
May 10, 2024 - In this approach, we slice the original string till the nth index, add the new character, followed by the slice of the original string after nth index. temp = 'pen' n = 1 new_temp = temp[: n] + 'i' + temp[n + 1:] print(new_temp) # displays pin ...
Discussions

python - Replace nth occurrence of substring in string - Stack Overflow
I want to replace the n'th occurrence of a substring in a string. There's got to be something equivalent to what I WANT to do which is mystring.replace("substring", 2nd) What is the simpl... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I replace the nth occurence of a substring/character within a string? [Python 3] - Stack Overflow
2 Python - How to replace all occurrences of a substring with consecutive number and save changes to main string? 1 How can I replace the first occurence of a sub-string in a string? 2 replace the nth character of a string (RegEx or not) More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - replace the nth character of a string (RegEx or not) - Stack Overflow
Let's consider the word 'APPLE', ... '], so l_string[4] is not the 4th underscore... 2021-01-31T21:20:05.553Z+00:00 ... Hi @XavierVillร Aguilar, you'll have to supply some code for me to comment. The function works fine: apple_masked = '_'*5 replace_nth_char(apple_masked,3,'L') Outputs: '____L_' Indexes in python start at 0 so the 4th character is position ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Replace every nth letter in a string - Stack Overflow
3 Python: replace every letter except the nth letters in a string with a period(or another character) More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ replace an nth character in string python | example code
Replace an nth character in string Python | Example code
June 9, 2023 - def replace_nth_character(string, n, new_char): string_list = list(string) # Convert string to list string_list[n - 1] = new_char # Replace nth character (indexing starts at 0) new_string = ''.join(string_list) # Convert list back to string return new_string # Example usage original_string = "Hello, World!" n = 7 new_character = 'X' modified_string = replace_nth_character(original_string, n, new_character) print(modified_string)
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 452362 โ€บ replace-nth-occurrence-of-any-sub-string-in-a-string
python - Replace nth occurrence of any sub string ... | DaniWeb
If you need the nth from the end, use rsplit(sub, n) instead of split. Note: This treats matches as non-overlapping, just like normal substring operations. If you need overlapping matches or pattern-based matching, a regex approach (for example, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-replacing-nth-occurrence-of-multiple-characters-in-a-string-with-the-given-character
Python โ€“ Replacing Nth occurrence of multiple characters in a String with the given character | GeeksforGeeks
January 15, 2025 - Given string str, a character ch, ... of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended ... We are given a string, and our task is to count how many times a specific character appears in it using Python...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-replacing-nth-occurrence-of-multiple-characters-in-a-string-with-the-given-character
Python - Replacing Nth occurrence of multiple characters in a String with the given character - GeeksforGeeks
July 12, 2025 - The code tracks occurrences of target characters (a, e, i) in the string. Upon finding the N-th occurrence, it replaces that character with * and exits the loop.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-replace-every-nth-character-in-string
Python Program to Take in a String and Replace Every Blank Space with Hyphen
August 17, 2023 - It takes two parameters, the blank space, and the value with which it needs to be replaced (hyphen in this case). ... my_string = input("Enter a string :") print("The string entered by user is :") print(my_string) my_string = my_string.replace(' ','-') print("The modified string:") print(my_string)
Top answer
1 of 16
29

You can use a while loop with str.find to find the nth occurrence if it exists and use that position to create the new string:

def nth_repl(s, sub, repl, n):
    find = s.find(sub)
    # If find is not -1 we have found at least one match for the substring
    i = find != -1
    # loop util we find the nth or we find no match
    while find != -1 and i != n:
        # find + 1 means we start searching from after the last match
        find = s.find(sub, find + 1)
        i += 1
    # If i is equal to n we found nth match so replace
    if i == n:
        return s[:find] + repl + s[find+len(sub):]
    return s

Example:

In [14]: s = "foobarfoofoobarbar"

In [15]: nth_repl(s, "bar","replaced",3)
Out[15]: 'foobarfoofoobarreplaced'

In [16]: nth_repl(s, "foo","replaced",3)
Out[16]: 'foobarfooreplacedbarbar'

In [17]: nth_repl(s, "foo","replaced",5)
Out[17]: 'foobarfoofoobarbar'
2 of 16
12

I use simple function, which lists all occurrences, picks the nth one's position and uses it to split original string into two substrings. Then it replaces first occurrence in the second substring and joins substrings back into the new string:

import re

def replacenth(string, sub, wanted, n):
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    print(newString)

For these variables:

string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5

outputs:

ababababCDabababab

Notes:

The where variable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with 0 usually, not with 1. Therefore there is a n-1 index and n variable is the actual nth substring. My example finds 5th string. If you use n index and want to find 5th position, you'll need n to be 4. Which you use usually depends on the function, which generates our n.

This should be the simplest way, but maybe it isn't the most Pythonic way, because the where variable construction needs importing re library. Maybe somebody will find even more Pythonic way.

Sources and some links in addition:

  • where construction: How to find all occurrences of a substring?
  • string splitting: https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string
  • similar question: Find the nth occurrence of substring in a string
Find elsewhere
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ -replace-n-th-occurrence-character-string
How to Replace the n-th Occurrence of a Character in a String? - CodingTechRoom
Copied ยท def replace_nth_occu... ''.join(result) Replacing the n-th occurrence of a specific character in a string can be achieved using a simple loop and a counter....
Top answer
1 of 2
2

I would approach this a bit differently:

The state at each point in time is defined by:

  • the full phrase (to be guessed),
  • a set of hidden words,
  • letters guessed so far (or to be revealed to the user).

The you can define a show() function with these three quantities:

def show(phrase, hidden_words, letters_guessed):
    parts = [
        ''.join([
            c if c in letters_guessed else '-' for c in w
        ]) if w in hidden_words else w
        for w in phrase.split()
    ]
    return ' '.join(parts)

With this, you can write tests, including doctests. That will make your code much easier to document, debug, test and use.

Some examples (which could be included as doctests in the docstring of show):

phrase = 'TO PIPE (STH) UP AND PIPE DOWN'
hidden_words = {'PIPE', 'UP'}

>>> show(phrase, hidden_words, {})
'TO ---- (STH) -- AND ---- DOWN'

>>> show(phrase, hidden_words, set('I'))
'TO -I-- (STH) -- AND -I-- DOWN'

>>> show(phrase, hidden_words, set('PI'))
'TO PIP- (STH) -P AND PIP- DOWN'
2 of 2
1

Given you're a rookie, I'd thought throw my hat in and do it without regex and attempt to explain. Maybe only read this once you've had your go. Your question title can be answered with:

def replace_nth_char(string, n, replacement):
    n -= 1
    l_string = list(string)
    l_string[n] = replacement
    return ''.join(l_string)

It converts the string to a list of letters which you can replace by index n and then joins it back up.

I've also given the rest a go to show you more python options.

As you're managing the state, you might want to think about using a class. It helps you wrap all the functions and attributes together into one object with a purpose - playing your Vocabulary Game. I recommend looking into them. Here is one for the game:

import random


class VocabularyGame():
    def __init__(self, chosen_words, hidden_words):
        self.chosen_words = chosen_words
        self.hidden_words = hidden_words
        self.hidden_letters = list(set(''.join(words)))
        self.masked_sentence = self.mask_words(chosen_words, hidden_words)
        print(f"Game start: {self.masked_sentence}")
        
    def mask_words(self, sentence, masks):
        return ' '.join(['_'*len(w) if w in masks else w for w in sentence.split(' ')])
    
    def try_letter(self, letter=None):
        if letter is None:
            letter = random.choice(self.hidden_letters)
        self.masked_sentence = ''.join(
            [c if c== letter else m for m, c in zip(self.masked_sentence, self.chosen_words)]
        )
        self.hidden_letters = [l for l in self.hidden_letters if l != letter]
        print(f"Trying letter {letter}...\nRemaining letters: {self.masked_sentence}")

The __init__ section runs whenever we make new game instances and takes three arguments, (self, chosen_words, hidden_words). The use of self references the current class instance (or game) and we can use it to set and retrieve attributes to the class, in this case, to remember our words and sentences.

    def __init__(self, chosen_words, hidden_words):
        self.chosen_words = chosen_words
        self.hidden_words = hidden_words
        self.hidden_letters = list(set(''.join(hidden_words)))
        self.masked_sentence = self.mask_words(chosen_words, hidden_words)
        print(f"Game start: {self.masked_sentence}")

list(set(''.join(words))) gets all unique letters in the hidden words by joining them into one string and using sets to convert them into the unique letters. I convert this back into a list for ease of use later.

We then apply a function to mask the words with '_'.

    def mask_words(self, sentence, masks):
        return ' '.join(['_'*len(w) if w in masks else w for w in sentence.split(' ')])

This goes through each word in the sentence and replaces it with '_' for the length of the word, if it exists in hidden words. Then it joins it back up. Now we have our start state.

The last thing to do is to try a letter. We do this by defining a method (function on a class) def try_letter(self, letter=None):. If no letter is provided, we pick a random one from the unique missing letters we defined earlier. The we go through each letter in the original sentence and masked sentence together using zip and when the original letter is our chosen letter, we replace the one in our masked sentence.

        self.masked_sentence = ''.join(
            [c if c==letter else m for m, c in zip(self.masked_sentence, self.chosen_words)]
        )

Then remove the letter form our hidden letters list:

self.hidden_letters = [l for l in self.hidden_letters if l != letter]

Finally, we print result out using f-strings. Now, we can play the game!

chosen_word = "TO CRANK (STH) UP"
words = ['CRANK', 'UP']

game = VocabularyGame(chosen_word, words)

Outputs: Game start: TO _____ (STH) __

Trying a letter 7 times for i in range(7): game.try_letter() Outputs:

Trying letter N...
Remaining letters: TO ___N_ (STH) __
Trying letter K...
Remaining letters: TO ___NK (STH) __
Trying letter R...
Remaining letters: TO _R_NK (STH) __
Trying letter P...
Remaining letters: TO _R_NK (STH) _P
Trying letter C...
Remaining letters: TO CR_NK (STH) _P
Trying letter U...
Remaining letters: TO CR_NK (STH) UP
Trying letter A...
Remaining letters: TO CRANK (STH) UP
Top answer
1 of 7
11

One-liner:

newstring = ''.join("*" if i % n == 0 else char for i, char in enumerate(string, 1))

Expanded:

def replace_n(string, n, first=0):
    letters = (
        # i % n == 0 means this letter should be replaced
        "*" if i % n == 0 else char

        # iterate index/value pairs
        for i, char in enumerate(string, -first)
    )
    return ''.join(letters)
>>> replace_n("hello world", 4)
'*ell* wo*ld'
>>> replace_n("hello world", 4, first=-1)
'hel*o w*orl*'
2 of 7
2

Your code has several problems:

First, the return in the wrong place. It is inside the for loop but it should be outside. Next, in the following fragment:

for i in range(len(str)):
    n=str[i]
    newStr=str.replace(n, "*")

the n that you passed as the second argument to your function is being overwritten at every loop step. So if your initial string is "abcabcabcd" and you pass n=3 (a number) as a second argument what your loop does is:

n="a"
n="b"
n="c"
...

so the value 3 is never used. In addition, in your loop only the last replacement done in your string is saved:

n="a"
newStr="abcabcabcd".replace("a", "*") --> newStr = "*bc*bc*bcd"
n="b"
newStr="abcabcabcd".replace("b", "*") --> newStr = "a*ca*ca*cd"
...
n="d"
newStr="abcabcabcd".replace("d", "*") --> newStr = "abcabcabc*"

If you test your function (after fixing the return position) with some strings it seems to work fine:

In [7]: replaceN("abcabcabc", 3)
Out[7]: 'ab*ab*ab*'

but if you do the choice more carefully:

In [10]: replaceN("abcabcabcd", 3)
Out[10]: 'abcabcabc*'

then it is obvious that the code fails and it is equivalent to replace only the last character of your string:

my_string.replace(my_string[-1], "*")

The code given by Eric is working fine:

In [16]: ''.join("*" if i % 3 == 0 else char for i, char in enumerate("abcabcabcd"))
Out[16]: '*bc*bc*bc*'

It replaces positions 3rd, 6th, 9th and so on. It may need some adjustment if you don't want the position 0 being replaced too.

๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ replace-character-string-python
Python Replace Character in String | FavTutor
October 6, 2021 - For this approach, you can make use of for loop to iterate through a string and find the given indexes. Later, the slicing method is used to replace the old character with the new character and get the final output.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ is there a way to replace the nth match in re.sub() with the nth value from a list?
r/learnpython on Reddit: Is there a way to replace the nth match in re.sub() with the nth value from a list?
January 27, 2023 -

I'm trying to work through a Mad Libs practice problem that seems like it should have a simple solution that I can't figure out.

I have a string of text containing placeholder words that the user is prompted to replace. Each word that the user inputs will be different. Is there a way to call them in order within re.sub()? An example of what I tried doing here:

import re

text = 'The ADJECTIVE brown fox jumps over the lazy NOUN.'
myRegex = re.compile(r'ADJECTIVE|NOUN')
wordPrompts = myRegex.findall(text)

user_inputs = []
for prompt in wordPrompts:
    user_inputs.append(input(f'Enter a {prompt.lower()}:\n'))

output = myRegex.sub(user_inputs[nth match goes here?], text)
print(output)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-string-replace-how-to-replace-a-character-in-a-string
Python string.replace() โ€“ How to Replace a Character in a String
September 1, 2022 - The new_char argument is the set of characters that replaces the old_char. The count argument, which is optional, specifies how many occurrences will be replaced. If this is not specified, all occurrences of the old_char will be replaced with the new_char. Let's see some examples. Here's an example that replaces "JavaScript" with "PHP" in a string: str = "I love JavaScript. I prefer JavaScript to Python because JavaScript looks more beautiful" new_str = str.replace("JavaScript", "PHP") print(new_str) # I love PHP.
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ string โ€บ python-data-type-string-exercise-9.php
Python: Remove the nth index character from a nonempty string - w3resource
June 12, 2025 - # Define a function named remove_char that takes two arguments, 'str' and 'n'. def remove_char(str, n): # Create a new string 'first_part' that includes all characters from the beginning of 'str' up to the character at index 'n' (not inclusive). first_part = str[:n] # Create a new string 'last_part' that includes all characters from the character at index 'n+1' to the end of 'str'. last_part = str[n+1:] # Return the result by concatenating 'first_part' and 'last_part', effectively removing the character at index 'n'. return first_part + last_part # Call the remove_char function with different input strings and character positions and print the results. print(remove_char('Python', 0)) # Output: 'ython' print(remove_char('Python', 3)) # Output: 'Pyton' print(remove_char('Python', 5)) # Output: 'Pytho'