简体   繁体   中英

How do I replace all instances of the first letter in a string, but not the first letter itself

My code so far is:

def ChangeString():
    print (userString.replace(
userString =str(input("Please enter a string "))
ChangeString()

In a string, I need to replace all instances of the first character with a *, without actually replacing the first character itself. An example is, let's say I have "Bobble"; the function would return something like, "Bo**le".

>>> test = 'Bobble'    
>>> test = test[0] +''.join(l if l.lower() != test[0].lower() else '*' for l in test[1:])
>>> print test

Bo**le

userString[0] + userString[1:].replace(userString[0], "*")

You could also use a regex:

import re

def ign_first(s, repl):
    return re.sub(r"(?<!^){}".format(s[0]), repl, s, flags=re.I)

Demo:

In [5]: s = "Bobble"

In [6]: ign_first(s, "*")
Out[6]: 'Bo**le'

Or use str.join with a set:

def ign_first(s, repl):
    first_ch = s[0]
    st = {first_ch, first_ch.lower()}
    return first_ch + "".join([repl if ch in st else ch for ch in s[1:]])

Demo:

In [10]: ign_first(s, "*")
Out[10]: 'Bo**le'

I would use slices and lower() .

>>> test = 'Bobble'
>>> test[0] + test[1:].lower().replace(test[0].lower(), '*')
'Bo**le'

There's no need to use additional variables

>>> st='Bobble'
>>> st=st[0]+st[1:].lower().replace(st[0].lower(),'*')
>>> st
'Bo**le'

case-insensitive solution with regular expressions:

import re

string = "Bobble"

outcome = string[0]+re.sub(string[0].lower() + '|' + string[0].upper(), 
                           "*", string[1:].lower())

>>>
Bo**le

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