Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string replacement except first character

Tags:

python

string

Writing a function that will replace every duplicate character of the first letter of a string with * except for the first letter itself - is there a more pythonic/elegant way to do it than this (lists, etc?)?

def specialreplace(s):
    firstchar = s[0]
    modifiedstr = s[1:].replace(firstchar, "*")
    print firstchar + modifiedstr

specialreplace('oompaloompa') ---> o*mpal**mpa
like image 401
SpicyClubSauce Avatar asked Jun 09 '15 19:06

SpicyClubSauce


1 Answers

It's a simple problem, I'm not sure why you're trying to complicate it. Your solution looks good, except for the fact that you should use .join() instead of '+' to join strings together.

"".join((s[0], s[1:].replace(s[0], "*"))
like image 194
eiLHW Avatar answered Oct 11 '22 03:10

eiLHW