user40720
user40720

Reputation: 89

Not able to remove characters from a string in Python

I am trying to loop through a string x that represents the alphabet and at the same time compare those values with a list that contains some specific letters.

If there is a match in both the list and the string x, it should remove the specific character from the string x. It is a very simple and straightforward piece of code. I've followed the .replace method to the T. However, when I ran the code, the string x still shows up in its original state.

Here is my working code:

lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']

x = 'abcdefghijklmnopqrstuvwxyz'

for i in range(len(x)):
    if x[i] in lettersGuessed:
        x.replace(x[i],'')

print x  "Available Letters"

Upvotes: 0

Views: 80

Answers (4)

nitimalh
nitimalh

Reputation: 961

You could use python sets to achieve this :

a = ['a','b','d']
b = "abcdefgh"
print ''.join(sorted(list(set(b) - set(a))))

output:

cefgh Available letters

Or use list comprehensions to achieve this :

a = ['a','b','d']
b = "abcdefgh"
print ''.join([x for x in b if x not in a])

Upvotes: 0

radsine
radsine

Reputation: 66

Try the following

x = x.replace(x[i], '')

You're not reassigning the changed value back to the original string.

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

You can use join and a generator expression:

print("Available Letters","".join(ch if ch not in lettersGuessed else "" for ch in x  ))

Using a loop, just iterate over the characters in lettersGuessed and update x each time:

 for ch in lettersGuessed:
     x = x.replace(ch,'') # assign the updated string to x


print("Available Letters",x)

Or iterating over x is the same logic:

for ch in x:
    if ch in lettersGuessed:
       x =  x.replace(ch,'')

strings are immutable so you cannot change the string in place. You need to reassign x to the new string created with x.replace(ch,'')

In [1]: x = 'abcdefghijklmnopqrstuvwxyz'    
In [2]: id(x)
Out[2]: 139933694754864    
In [3]: id(x.replace("a","foo")) # creates a new object
Out[3]: 139933684264296
In [7]: x 
Out[7]: 'abcdefghijklmnopqrstuvwxyz' # no change     
In [8]: id(x)
Out[8]: 139933694754864 # still the same object

Upvotes: 0

Tomalak
Tomalak

Reputation: 338396

Simple mistake.

x = x.replace(x[i],'')

Upvotes: 1

Related Questions