0

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".

The White Wolf
  • 65
  • 1
  • 2
  • 8

6 Answers6

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

Bo**le
xiº
  • 4,605
  • 3
  • 28
  • 39
1

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

P.Melch
  • 8,066
  • 43
  • 40
1

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'
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

I would use slices and lower().

>>> test = 'Bobble'
>>> test[0] + test[1:].lower().replace(test[0].lower(), '*')
'Bo**le'
BlivetWidget
  • 10,543
  • 1
  • 14
  • 23
0

There's no need to use additional variables

>>> st='Bobble'
>>> st=st[0]+st[1:].lower().replace(st[0].lower(),'*')
>>> st
'Bo**le'
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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
  • 1
    You will also end up changing all the string to lower, the replacement should be case insensitive but that does not mean every letter is lowercase – Padraic Cunningham Oct 13 '15 at 20:32
  • Thank you for the observation Padraic! I edited my answer. It should work now. All occurrences of the first letter are substituted in the word, no matter whether they are upper or lower case, without changing the original string. – Jose Haro Peralta Oct 13 '15 at 20:41
  • I just saw that you actually posted the same solution shortly before me ^^" haha, sorry for the duplication – Jose Haro Peralta Oct 13 '15 at 20:43
  • You would need re.I. if you had an uppercase letter in the string like the first lettter of a name, place etc..you would also lower that. The logic needs to do a case insensitive replacement but leave the rest of the string as is. – Padraic Cunningham Oct 13 '15 at 20:54