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 OverflowI'm trying to replace every third character in a string, but it's not working. Here is my code:
s=str(input())
dv3=[::3]
print(s.replace(dv3,"a"))
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*'
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.
python - How to replace every third word in a string with the # length equivalent - Stack Overflow
substring - How do I print a string without every third charater in python? - Stack Overflow
text processing - Cut and replace Nth character on every row - Unix & Linux Stack Exchange
How to select every nth in a long string of characters?
I solved it with:
s = "My dear adventurer, do you understand the nature of the given discussion?"
def replace_alphabet_with_char(word: str, replacement: str) -> str:
new_word = []
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for c in word:
if c in alphabet:
new_word.append(replacement)
else:
new_word.append(c)
return "".join(new_word)
every_nth_word = 3
s_split = s.split(' ')
result = " ".join([replace_alphabet_with_char(s_split[i], '#') if i % every_nth_word == every_nth_word - 1 else s_split[i] for i in range(len(s_split))])
print(result)
Output:
My dear ##########, do you ########## the nature ## the given ##########?
Following works and does not use regular expressions
special_chars = {'.','/','|','?','!','_','"',',','-','@','\n','\\'}
def format_word(w, fill):
if w[-1] in special_chars:
return fill*(len(w) - 1) + w[-1]
else:
return fill*len(w)
def obscure(string, every=3, fill='#'):
return ' '.join(
(format_word(w, fill) if (i+1) % every == 0 else w)
for (i, w) in enumerate(string.split())
)
Here are some example usage
In [15]: obscure(string)
Out[15]: 'My dear ##########, do you ########## the nature ## the given ##########?'
In [16]: obscure(string, 4)
Out[16]: 'My dear adventurer, ## you understand the ###### of the given ##########?'
In [17]: obscure(string, 3, '?')
Out[17]: 'My dear ??????????, do you ?????????? the nature ?? the given ???????????'
An input string is immutable, but convert it to a list and you can edit it:
>>> word = list(input()) # Read in a word
abcdefghijklmnop
>>> del word[::3] # delete every third character
>>> ''.join(word) # join the characters together for the result
'bcefhiklno'
Starting at a different character:
>>> word = list(input())
123123123123
>>> del word[2::3]
>>> ''.join(word)
'12121212'
Check this out:
>>> word = 'Python For All'
>>> new_word = ''.join(character for index, character in enumerate(word) if index%3 != 0)
>>> new_word
'ytonFo Al'
Find: ([^\|]*\|[^\|]*)\|
Replace to: \1\n
I want to replace every second instance of | with a new line
Menu "Search" > "Replace" (or Ctrl + H)
Set "Find what" to
(.*?\|.*?)[\|]Set "Replace with" to
\1\r\nEnable "Regular expression"
Click "Replace All"

Before:
Name1|Value1|Name2|Value2|Name3|Value3
After:
Name1|Value1
Name2|Value2
Name3|Value3
Notes:
The above assumes you are editing a text file with Windows EOLs,
\r\n.If you are using files with different EOLs you can convert them to Windows EOLs using Menu "Edit" > "EOL Conversion".
If you aren't working with Windows EOL, and you don't wish to convert them, use the following instead:
Use
\ninstead of\r\nfor Unix/OS X EOLsUse
\rinstead of\r\nfor Mac OS (up to version 9) EOLs
Further reading
- Notepad++: A guide to using regular expressions and extended search mode
The simplest way given your example input is to just replace the first comma-and-space with an x (here, file has your example):
$ sed 's/, /x/' file
775448167763476486x783834143007506433, 35972, 35972,
775448167763476486x844395243412914178, 408008, 408008,
775448167763476486x891964514511355905, 8003, 8003,
783834143007506433x891655551753846784, 66633, 66633,
That has the benefit of working irrespective of the length of the first field. If you must change the 19th and 20th characters, you could do:
$ sed 's/../x/10' file
775448167763476486x783834143007506433, 35972, 35972,
775448167763476486x844395243412914178, 408008, 408008,
775448167763476486x891964514511355905, 8003, 8003,
783834143007506433x891655551753846784, 66633, 66633,
The trick here is that the /10 means "repace the tenth occurrence of the pattern" and since the pattern is .., so two characters, it will change the 19th and 20th.
If you need to replace the 19th and 20th character of each line with x if and only if they are , and space respectively, you can do:
sed 's/^\(.\{18\}\), /\1x/'
With most sed implementations (all those compliant to POSIX 2024), that can be made more legible by switching from basic to extented regexp with -E:
sed -E 's/^(.{18}), /\1x/'