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*'
Answer from Eric on Stack Overflow
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.

Discussions

python - How to replace every third word in a string with the # length equivalent - Stack Overflow
Input: string = "My dear adventurer, do you understand the nature of the given discussion?" expected output: string = 'My dear ##########, do you ########## the nature ## the given #####... More on stackoverflow.com
🌐 stackoverflow.com
substring - How do I print a string without every third charater in python? - Stack Overflow
I'm currently trying to do this challenge where it gives me a string, such as 'Python' and I need to remove every third character, or every character which index is divisible by 3. In this example,... More on stackoverflow.com
🌐 stackoverflow.com
text processing - Cut and replace Nth character on every row - Unix & Linux Stack Exchange
I have predictable piped input, I want to iterate over each row and change two characters. the character positions are 19 and 20 (on every row.) The 19th character is a comma, I want to cut that. The More on unix.stackexchange.com
🌐 unix.stackexchange.com
June 26, 2024
How to select every nth in a long string of characters?
Not really with functions, if it is a one-off you can approximate it with array formulas but it still takes fidgeting and manual work. Really, making a macro is the only way to do it perfectly. If you can use any number of cells you could just use =MID(A2,row(A1)+column(A1)*5,1) and drag it over for as many columns as you needed and down for as many increment increases, then concatenate them together afterwards in another column where you can just drag down the concatenate formula after you write it out once, this still isn't pretty but it's pretty straight forward at least. More on reddit.com
🌐 r/excel
3
3
January 6, 2015
🌐
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 - Using slicingSlicing is one of the most efficient ways to replace a character at a specific index. [GFGTABS] Python s = "h ... Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e.
🌐
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)
🌐
You.com
you.com › search › replace every third character in string python
replace every third character in string python 🔎 You.com | Accurate Answers & Agents
Leverage a personal AI search agent & customized recommendations with You.com's AI chatbot. Converse naturally and discover the power of AI. Chat now!
🌐
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 - Using replace()replace () method is the most straightforward and efficient way to replace all occurrence ... In Python, we can replace characters in a string dynamically based on a dictionary.
🌐
Snakify
snakify.org › en › lessons › strings_str › problems › delete_every_third_char
Solve problem "Delete every third character" online - Learn Python 3 - Snakify
5. Strings · Slices · The number of words · The two halves · To swap the two words · The first and last occurrence · The second occurrence · Remove the fragment · Reverse the fragment · Replace the substring · Delete a character · Replace within the fragment · Delete every third character ·
Find elsewhere
🌐
Instagram
instagram.com › p › CPw8dCoL7Ol
Replace every nth character with given string.
June 5, 2021 - Create an account or log in to Instagram - Share what you're into with the people who get you.
🌐
Snakify
snakify.org › strings
Strings - Learn Python 3 - Snakify
That is, to remove the last character from the string, you can use slice S[:-1]. The slice S[:] matches the string S itself. Any slice of a string creates a new string and never modifies the original one.
🌐
W3Schools
w3schools.com › python › ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase.
🌐
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.
🌐
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 use list() function to convert the string into a list. Then we replace the desired character using its index. Then we convert python list back into string using join() function.
🌐
Medium
medium.com › @pies052022 › python-string-replace-method-explanation-with-example-program-3fbd2f33f812
Python String replace() Method: Explanation with Example Program | by JOKEN VILLANUEVA | Medium
March 13, 2026 - The string ‘PHP is replaced by a new string Python, and it will print Python is Nice. ... Using the Python .replace() function, you may replace every occurrence of a certain character with another.
🌐
Mimo
mimo.org › tutorials › python › how-to-replace-characters-in-a-string-in-python
How to Replace Characters in a String in Python
Replace characters in Python strings with replace() or translate(), including limits and multi-character swaps.
🌐
StrataScratch
stratascratch.com › blog › how-to-replace-a-character-in-a-python-string
How to Replace a Character in a Python String - StrataScratch
October 18, 2024 - This article taught you the three main techniques for replacing a character in a Python string: str.replace() – for straightforward replacements · List comprehension – for flexible replacements and complex conditions ... It also demonstrated how to use these techniques in three practical examples from the StrataScratch choice of coding interviews. Most important, however, is that you’ll become the life of every party with the information that strings in Python are immutable, and changing them doesn’t change them at all; it creates a new string!
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - Read, write, and create files in Python (with and open()) The replace() method replaces all occurrences of a substring with another. ... Provide the substring to replace as the first argument (old) and the new substring as the second (new). ...