>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
Answer from mg. on Stack Overflow>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
Here is a one-liner:
result = new.join(s.rsplit(old, maxreplace))
Return a copy of string s with all occurrences of substring old replaced by new. The first maxreplace occurrences are replaced.
and a full example of this in use:
s = 'mississipi'
old = 'iss'
new = 'XXX'
maxreplace = 1
result = new.join(s.rsplit(old, maxreplace))
>>> result
'missXXXipi'
Remove Last Occurrence of Letter
python - Finding last occurrence of substring in string, replacing that - Stack Overflow
python - Which method is faster for replacing the last occurrence of a substring in a string? - Stack Overflow
python - To replace but the last occurrence of string in a text - Stack Overflow
Hello everyone, I have a question about a problem that I actually have already solved. The task goes like this:
Write a function that removes the last occurence of a given letter in a given string. If the given letter does not appear in the string then remove the first letter of that string.
So in the code under the text you can see that I solved the task. I feel like I overcomplicated things. I don't know how I could simplify it. Any tips?
///Edit: probably should've noted that I cannot use rfind
def removeLetter(string,letter):
newWord = str()
index = 0
newString = str()
originalString = str()
for char in string:
newString = char + newString
for char in newString:
if char==letter:
index=newString.index(char)
newWord = newString[:index] + newString[(index+1):]
for char in newWord:
originalString = char + originalString
if letter not in string:
print(string[1:])
else:
print(originalString)
removeLetter("testing", "t")This should do it
old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]
To replace from the right:
def replace_right(source, target, replacement, replacements=None):
return replacement.join(source.rsplit(target, replacements))
In use:
>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
This is one way:
>>> s = 'CSsomethingSCSagainCSsomething'
>>> 'SC'.join(s.rsplit('CS', 1))
CSsomethingSCSagainSCsomething
Syntax:
new_substring.join(str.rsplit(old_substring, occurance))
In my crude timing, this beats the rsplit() and join() solution by 20%:
head, _, tail = string.rpartition('CS')
new_string = f"{head}SC{tail}"
I does depend on Python 3.6+, of course.
str.replace() method has a count argument:
str.replace(old, new[, count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Then, use str.count() to check how many and in the string and then -1 (because you need the last and):
str.count(sub[, start[, end]])Return the number of non-overlapping occurrences of substring sub in the range
[start, end]. Optional arguments start and end are interpreted as in slice notation.
Demo:
>>> string = 'Saturday and Sunday and Monday and Tuesday and Wednesday and Thursday and Friday are days of the week.'
>>> string.replace(' and ', ", ", (string.count(' and ')-1))
'Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday and Friday are days of the week. '
If you want a regex solution, you could match all the ands which are followed by another one later in the string.
>>> str='Monday and Tuesday and Wednesday and Thursday and Friday and Saturday and Sunday are the days of the week.'
>>> import re
>>> re.sub(' and (?=.* and )', ', ', str)
'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday are the days of the week.'
(?=...) is a lookahead which makes sure there is a match later in the string without including it in the actual match (so also not in the substitution). It's sort of like a conditional on the match.