+ 1

Pls how do i subtract strings?

for example: name = 'Sololearn', namer = Solo, namest = 'learn', nameful = 'lole name - namer = 'learn', name - namest = 'Solo'', name-nameful = 'Soarn' I tried three methods but i doesn't work for all cases 1. using list(set(list))) but this had issues with double letters 2. using str.rstrip() but it failed when in cases like (Sololearn - Solo) 3. using str.strip() but it failed in cases like (SololearnSolo - Solo) P.S I'm trying to create an __sub__ magic method in a particular class i created

1st Jul 2021, 11:34 PM
Nwalozie Elijah
Nwalozie Elijah - avatar
7 Answers
+ 3
def __sub__(self, other): return self.replace(other, '', 1) Where self and other are both str objects this would remove the first found substring of other in self and return the new string. Here's an example where I extend the str class and use a Mixin for the sub magic method. https://code.sololearn.com/cUlDU0ddJ1G3/?ref=app
2nd Jul 2021, 1:02 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
ChaoticDawg Thanks man. I'll try it in my code
2nd Jul 2021, 1:05 AM
Nwalozie Elijah
Nwalozie Elijah - avatar
+ 1
Why does name-namer='learn' ?
1st Jul 2021, 11:53 PM
Abhay
Abhay - avatar
+ 1
@Abhay, SOLOLEARN - SOLO = LEARN
2nd Jul 2021, 1:04 AM
Nwalozie Elijah
Nwalozie Elijah - avatar
0
So i tried a few more methods including the one by ChaoticDawg and there were always different bugs in different cases so i came to the conclusion that strings are not built for the '-' operator
2nd Jul 2021, 4:06 PM
Nwalozie Elijah
Nwalozie Elijah - avatar
2nd Jul 2021, 4:07 PM
Nwalozie Elijah
Nwalozie Elijah - avatar