简体   繁体   中英

Unexpected output in python program

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. eg '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'))

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(), '*')

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

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'))

Quite 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

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