Adrian
Adrian

Reputation: 13

issue in removing a specific character in a string

i keep getting TypeError: can only join an iterable. I am trying to remove a specific character from a string in python.

def get_2s_and_5s_removed(dice_string):   
    dice_string =list(dice_string)
    if '2' in dice_string:
      dice_string =dice_string.remove('2')
      return ''.join(dice_string)
    if '5' in dice_string:
      dice_string =dice_string.remove('5')
      return ''.join(dice_string)**

Upvotes: 1

Views: 43

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177481

Assuming you want to remove all 2s and 5s as the function name implies, all you really need is .replace:

>>> '11223245565'.replace('2','').replace('5','')
'11346'

Upvotes: 3

Jake Conway
Jake Conway

Reputation: 909

Python's remove method modifies the list itself and doesn't return a new list containing the original list minus the removed values. The correct way to use it would be: dice_string.remove('2') (i.e. don't use an equal sign with it, as it will assign NoneType to the variable).

Upvotes: 3

Related Questions