1

A list of original strings:

Originals = ["nice apple", "orange", "pear sweet", "red ape"]

A list of strings to remove:

To_remove = ["nice ", " sweet"]

What I want to achieve is to remove the strings needed to be removed in each elements in the original words

result: ["apple", "orange", "pear", "red ape"]

I do following but it doesn’t produce a good result.

for t in To_remove:
    for o in Originals:
        print o.replace(t, "")

what would be the right way? Thank you.

Mark K
  • 8,767
  • 14
  • 58
  • 118
  • 1
    *`but it doesn’t produce a good result`* -- **What do you see**? Please show us! – Wolf Feb 03 '17 at 09:04
  • Your questions title is quite confusing, maybe you should reword it to match your actual need. – Wolf Feb 03 '17 at 09:27
  • Suggestion for a catching title: **Howto "censor" a string list in python?** :-) – Wolf Feb 03 '17 at 10:12

4 Answers4

4

Strings are immutable. Hence, none of the methods you can call on a string does an in-place modification. They all return a new string, so you have to reassign the string returned by replace:

for t in To_remove:
    for i in range(len(Originals)):
        Originals[i] = Originals[i].replace(t, "")

You can check out this question for how to merge the replacement of multiple patterns.

Community
  • 1
  • 1
user2390182
  • 72,016
  • 6
  • 67
  • 89
3

Because string is immutable, you have to reassign the list element.

for t in To_remove:
    for i, o in enumerate(Originals):
        Originals[i] = o.replace(t, "")

print Originals 

hope this helps.

Wolf
  • 9,679
  • 7
  • 62
  • 108
thangtn
  • 856
  • 6
  • 7
1

You are printing the results of the replacement, but do not change the list contents. If you have a closer look on the replace method (for strings(!)), you'll see that you are not only not changing the list but also not changing the strings you are getting for o in Originals. I omit including a working example, since schwobaseggl and thangtn [1] already provide it.


[1] Who was really first? The SO timestamps contradict my personal experience.

Community
  • 1
  • 1
Wolf
  • 9,679
  • 7
  • 62
  • 108
  • BTW: the [official docs](https://docs.python.org/3/library/stdtypes.html#str.replace) are very sparse, maybe this is the reason you have so bad Google results for it. – Wolf Feb 03 '17 at 09:42
1
Originals = ["nice apple", "orange", "pear sweet", "red ape"]
To_remove = ["nice ", " sweet"]
result = []

for o in Originals:
    for t in To_remove:
        result.append(o.replace(t, ""))

print result

Is that what you need?

Wolf
  • 9,679
  • 7
  • 62
  • 108
Dev Jalla
  • 1,910
  • 2
  • 13
  • 21
  • Some more text may help to understand the purpose of the repetition of the already known. – Wolf Feb 03 '17 at 09:37
  • ...I have to correct myself about this (concerning *'repetition'*) you don't an in-place replacement. A valid option. – Wolf Feb 03 '17 at 17:58