-1

Below is a simple piece of code that accepts 2 strings and removes all characters from the 2nd string which are present in the 1st string:

s1 = 'aeiou'
s2 = 'this is python program'

checkFor = []
for i in s1:
  checkFor.append(i)

for i in s2:
  if i in checkFor:
    print(i)
    s2.replace(i, '')

print(s2)

This is the output I'm getting:

i
i
o
o
a
this is python program

The if block is getting executed but why is the .replace() method not working? or is there a better way of deleting a character from a string?

  • 1
    `.replace()` *is* working. You're just not doing anything with the new string that it produces. – jasonharper Aug 13 '21 at 21:02
  • in addition to answers below, how about using list comprehensions instead? `''.join([i for i in s2 if i not in s1])` – cmbfast Aug 13 '21 at 21:05

2 Answers2

0

You are not assigning the value of replace:

s2 = s2.replace(i, '')
Mohammad
  • 3,276
  • 2
  • 19
  • 35
0

Save s2.replace() somewhere and print it.

for i in s2:
  if i in checkFor:
    print(i)
    s2 = s2.replace(i, '')

print(s2)
xtryingx
  • 152
  • 7