Replace string space with given character in Python

In this tutorial we are going to learn writing python program to replace the string space with given character.

Problem Statement

For a given string we have to replace all the spaces with the character given by the user as an input.

For example:

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.

Python code to replace the string space with given character

# Taking input from the user
string = input("Enter a string: ")
ch = input("Enter a character to replace spaces: ")

result = ''  # Empty string to store the result

# Iterating using a for loop
for i in string:
    if i == ' ':      # If space is found
        i = ch        # Replace it with the given character
    result += i       # Append the character to the result

# Printing the modified string
print("String after replacing spaces with", ch, "=", result)

Output:

Enter a string: quescol website
Enter a character to replace spaces: C
String after replacing spaces with C = quescolCwebsite

What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now