Let's say I have the following:
str1='restart'
I want to replace 'r' with '#' but only the second occurrence of 'r' and not the first, using the function replace()
Expected return is:
str1='resta#t'
I know how to replace either all the occurrences of 'r' str1.replace('r','#')
, or a number of occurrences of 'r' starting from the first one str1.replace('r','#',1)
, but cannot figure how to replace just the second occurrence and not the other ones.
CodePudding user response:
If this doesn't solve the problem then I need more detail.
str1.replace(str1[5],'#')
or
r2 = str1.find(r, 2)
str1.replace(r2, '#')
CodePudding user response:
The following code does the trick.
string = "restart"
result = string.replace("r", "#").replace("#", "r", 1)
print(result) # resta#t
CodePudding user response:
You can use split and replace for the same.
str1 = "restart"
split_ch = "r"
new_ch = "#"
split_list = str1.split(split_ch, 1)
result = split_list[0] split_ch split_list[1].replace(split_ch,new_ch, 1)
CodePudding user response:
We can use a regex replacement here:
str1 = "restart"
output = re.sub(r'r([^r]*)r', r'r\1#', str1, 1)
print(output) # resta#t
The pattern matches the first r
, captures optional non r
following letters, followed by the second r
. We then replace, swapping in #
for the second r
. Note that the fourth parameter to re.sub
is 1
, meaning that this replacement will only happen once.
CodePudding user response:
str1='restart'
str1 = [*str1]
i = 0
j = 0
for string in str1:
j = 1
print(string, j)
if string == 'r':
i =1
if i ==2:
str1[j-1] = '#'
else:
continue
print(''.join(str1))
Definitely not the best, but this works...
CodePudding user response:
One way that maybe gets it done for you!
def replace_second(input_:str, letter:str = 'r', replace:str ='other'):
idx = [i for i, _ in enumerate(input_) if _ ==letter]
return input_[:idx[1]] input_[idx[1]:].replace(letter, replace)
Try it out yourself:
replace_second('restart', 'r', '#')