In this tutorial we are going to learn writing python program to replace the string space with given character.
For a given string we have to replace all the spaces with the character given by the user as an input.
Case 1: If user is given the string value as ‘ques ol’,
and the character value inserted by user is ‘c’
then the output generated must be “quescol”.
Case 2: If user is given the string value as ‘python sfun’,
and the character value inserted by user is ‘i’
then the output generated must be “pythonisfun”.
Our logic to replace a string with given character
- In order to replace a string with any character, we need to take a string and a character as an input from the user using the ‘input()’ function.
- Then, using for loop, we iterate through each element of string and search for “ “ (space).
- If “ “(space) is found replace it with character.
- Finally, the result will be returned as the output of our program.
Algorithm to replace a string with given character
Step2: Take a string and a character as input from the user.
Step 3: Create an empty string, as result = “ ”
Step4: Use for loop to iterate through the string.
Step5: if space_found:
i = character
result +=i ( concatenate the characters of string)
Python code to replace the string space with given character
As we can observe the string returned is without any space and all spaces from the input string are replaced with character ‘t’.