简体   繁体   中英

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

 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!

Here is one option:

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

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)

You can replace list comprehension with generator expression in @OfirY's answer like so:

choice = 'Lillian'
firstpick = 'l'
''.join(c if c == firstpick else '-' for c in choice)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM