繁体   English   中英

替换字符串中除一种类型之外的所有字符:Python

[英]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,'-'))

此代码所需的 output 应该是“l-ll---”但它是“l-ll-an”“l-ll-an”“lilli-n”“lillia-”

对此感到抱歉,我不是最擅长代码,但我会很感激一个解决方案。 谢谢!

这是一种选择:

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

字符串是不可变的,因此您需要存储替换的结果。 尝试这个:

choice = "lillian"
firstpick = "l"

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

print(choice)

您可以在@OfirY 的答案中用生成器表达式替换列表理解,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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