Home > Net >  Replacing all but one type of character in a string: Python
Replacing all but one type of character in a string: Python

Time:01-01

 choice = "lillian"
 firstpick = "l"

 for n in choice:
    if n != firstpick:
       inverse = n
       if inverse in choice:
           print(choice.replace(inverse,'-'))

The desired output of this code would have been "l-ll---" but it was "l-ll-an" "l-ll-an" "lilli-n" "lillia-"

Sorry about this, I'm not the best at code but I'd appreciate a solution. Thanks!

CodePudding user response:

Here is one option:

choice = "lillian"
firstpick = "l"
''.join([c if c==firstpick else '-' for c in choice])

CodePudding user response:

Strings are immutable, so you'll need to store the result of the replacement. Try this:

choice = "lillian"
firstpick = "l"

for letter in choice:
    if letter != firstpick:
       choice = choice.replace(letter, '-')

print(choice)
  • Related