0

I'm trying to remove a set of characters from a larger string. Here's what I've tried:

string = 'aabc'
remove = 'ac'
for i in remove:
    string.replace(i, '', 1)
print(string)

I keep getting back my original string when I run this. The variable i is getting the characters 'a' and then 'c'. The replace function works for me if i do string.replace('a', '', 1). Why isn't this working or is there a simpler way to do this?

StevenWhite
  • 5,907
  • 3
  • 21
  • 46
  • help(str.replace) --> _Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced._ – tdelaney Nov 13 '14 at 18:28

4 Answers4

5

Strings are immutable in python, so string.replace() does not mutate the string; it returns a new string with the replacements.

Try this:

string = string.replace(i, '', 1)
gcarvelli
  • 1,580
  • 1
  • 10
  • 15
2

replace returns a new string.

Strings in python are immutable.

As such, you must assign the return value:

string_new = "ABCD".replace("A","Z")
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

A new string will be generated as Strings are immutable...

Try this -

string = 'aabc'
remove = 'ac'
for i in remove:
    result = string.replace(i, '', 1)
print(result)
user1050619
  • 19,822
  • 85
  • 237
  • 413
0

As Strings are immutable you cant use replace with just string.replace(). As a better way use set :

>>> s='aabcc'
>>> s=''.join(set(s))
'acb'
Mazdak
  • 105,000
  • 18
  • 159
  • 188