Home > other >  Find And Replace Character In Python
Find And Replace Character In Python

Time:10-25

For the get_letter_from_user function, while using the while loop for validation, it keeps repeating the invalid input; I want to make sure that it is a single letter and lower case, and I want to make sure that it doesn't equal the second parameter of the function. I'm not sure what I'm doing wrong, though. (and how to get gud at coding if u have tips)

def get_text_from_user(prompt):
    return input(prompt).lower()
    
    
    
    
def get_letter_from_user(prompt, not_allowed):          
    not_allowed = ''
    
    allowed = input(prompt).lower()
    while not allowed == not_allowed or allowed.isalpha() or len(allowed) > 1:
        allowed = str(input('Invalid letter, try again:'))
        
    
    return allowed
    
    
    
    
def main():
    text = get_text_from_user("Enter some text: ")
    ltr1 = get_letter_from_user("Enter a letter: ", '')  
    ltr2 = get_letter_from_user("Enter another letter: ", ltr1)  
    new_text = text.replace(ltr1,ltr2)
    print("The new text is", new_text)
    
    
if __name__ == "__main__":
    main()

CodePudding user response:

Suggestion for the function:

def get_letter_from_user(prompt, not_allowed):

    allowed = input(prompt).lower()
    while allowed == not_allowed or len(allowed) > 1:
        print('not_allowed:',not_allowed)
        allowed = str(input('Invalid letter, try again:'))

    return allowed


ltr1 = get_letter_from_user("Enter a letter: ", '')  
ltr2 = get_letter_from_user("Enter another letter: ", ltr1)  

Sample output:

Enter a letter: d
Enter another letter: d
not_allowed: d
Invalid letter, try again:d
not_allowed: d
Invalid letter, try again:a

CodePudding user response:

To replace a letter or sequence of letters in a string, you might want to take a look at the string.replace() function:

text = input('Enter some text: ')
find = input('Enter a letter to replace: ')
replace_with = input(f'Enter a letter to replace \'{find}\' with: ')
replaced = text.replace(find, reolace_with)
print('The new text is:', replaced)

CodePudding user response:

To add another little detail because you asked how to get better at coding:

I would never make a function with a parameter that is immediately changed to an empty string. Like:

def get_letter_from_user(prompt, not_allowed):
    not_allowed = ''

Rather use a default value like this:

def get_letter_from_user(prompt, not_allowed=''):
    ...
  • Related