编写一个函数,用*替换字符串第一个字母的每个重复字符除了第一个字母本身 - 是否有更多的pythonic /优雅方式来做这个(列表等?)?
def specialreplace(s):
firstchar = s[0]
modifiedstr = s[1:].replace(firstchar, "*")
print firstchar + modifiedstr
specialreplace('oompaloompa') ---> o*mpal**mpa
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个简单的问题,我不确定你为什么要把它复杂化.您的解决方案看起来不错,除了您应该使用.join()而不是'+'将字符串连接在一起.
"".join((s[0], s[1:].replace(s[0], "*"))
Run Code Online (Sandbox Code Playgroud)
您已经在使用列表索引和切片,并且您有一个干净的答案。仍然:
def specialreplace(s):
chars = [ ('*' if c == s[0] else c) for c in s[1:] ]
print s[0] + ''.join(chars)
Run Code Online (Sandbox Code Playgroud)
如果你想编写高尔夫代码:
specialreplace = lambda s:s[0]+''.join(['*'if c==s[0]else c for c in s[1:]])
Run Code Online (Sandbox Code Playgroud)
编辑时将带有默认返回值的字典查找铲入其中,因为为什么不使用厨房水槽:
specialreplace=lambda s:s[0]+''.join([{s[0]:'*'}.get(c,c)for c in s[1:]])
Run Code Online (Sandbox Code Playgroud)
编辑:@Voo 的评论,列表理解相当 Pythonic - 如果您必须按照 SpicyClubSauce 的要求使用字符列表,那么您就拥有与 Python 一样接近的三元运算符,以及将字符列表重新组合在一起的连接。lambda 版本非常不Pythonic。所有这些都没有提问者最初的解决方案优雅。