I have copied the following code with some alteration in naming to solve the problem as stated: Given a string s, return a string where all occurences of its first char have been changed to '*', except do not change the first char itself. e.g. 'babble' yields 'ba**le'. Assume that the string is length 1 or more. Here is the code: My question is when I pass "Lulla" why don't I see "Lu**a" returned in the interpreter as I think the code should do.
def fix_start(s):
start_letter = s[0]
rest_letters = s[1:]
rest_letters = rest_letters.replace(start_letter,'*')
return start_letter + rest_letters
print (fix_start ('Lulla'))
-
since your replacing with Captial L but others r small lsundar nataraj– sundar nataraj2014年07月07日 04:52:13 +00:00Commented Jul 7, 2014 at 4:52
4 Answers 4
What happens is that Python is case-sensitive. In other words:
'L' != 'l'
So, when you do
rest_letters = rest_letters.replace(start_letter,'*')
it will replace all occurences of only L, not both L and l.
What can you do? The process of case-insensitive replacing is kind of complex, as you can see in these answers. But in your case, this may work:
rest_letters = rest_letters.replace(start_letter,'*').replace(start_letter.lower(), '*')
1 Comment
"luLLa"? You should use start_letter.upper() to cover that possibilityQuite simply all that is required is to use lower() or upper() to change the string case:
start_letter = s[0].lower()
rest_letters = s[1:].lower()
Input: LulLa
Output: lu**a
2 Comments
return s[0] + rest_letters.In your code, you are replacing any instance of the first letter "L" in the remainder of the string. In the case of the example, "Lulla", the first letter is a capital "L", and is not equal to "l". As such, I would try the following:
def fix_start(s):
start_letter = s[0]
rest_letters = s[1:]
rest_letters = rest_letters.replace(start_letter.lower(),'*')
return start_letter + rest_letters
The above solution will work if you have strings that are guaranteed to be syntactically correct (as in no uppercase letters in the middle of the word).
If that is not guaranteed, go ahead and try this:
def fix_start(s):
start_letter = s[0]
rest_letters = s[1:]
rest_letters = rest_letters.replace(start_letter.lower(),'*')
rest_letters = rest_letters.replace(start_letter, '*')
return start_letter + rest_letters
Comments
Actually your trying to replace L but rest of the characters are small l.Try using regular expression that makes this task easy.
import re
def fix_start(s):
start_letter = s[0]
regex = s[0].lower()+"|"+s[0].upper()
rest_letters = s[1:]
rest_letters = re.sub(regex, "*", rest_letters)
return start_letter + rest_letters
print (fix_start ('Lulla'))