Python Program to Replace Selected Character with * in a String
Python Program to Replace Selected Character with * in a String
Hey There Python Geeks,
In this python tutorial, I have shown how to replace selected character with * in a string.
Consider a string : str = "hello youtube'
For character we ask the user to select a character : char = input("Enter a character that can be replaced")
Create a function called replace_char and pass the string(str) to it, you can name a function whatever you want and that can be done as : def replace_char(str):
To check for every element we use for loop and can be written as : for i in str:
If the character and the element which is in the string matches exactly the same, we need to replace it with *, that can be done as : if char==i:
str.replace(char , " ")
And at last we need to return the string(str) : return str.replace(char , " ")
We successfully replaced the character with * which is present in the string, now what if a character is not present in the string?. For that we can use else statement to print character is not present in the string(str) that can be done as : else:
return "Selected character is not present in the string"
Now, the code can be written as :
str = "hello youtube"
char = input("Enter a character to be replaced")
def replace_char(str):
for i in str:
if char==i:
else:
print(replace_char(str))
Comments
Post a Comment