Instagram
youtube
Facebook
Twitter

Replace Spaces in a String using replace() Method

A Python program that replaces all spaces in a string with a specified character using the built-in replace() method.

Code Explanation Step by Step

Function Definition: replace_space(string, char) is created to replace spaces in the string.
 

Using replace() Method: string.replace(" ", char) replaces all spaces with the given character.
 

Take User Input:
 

  • string = input("Enter a string: ") takes a string from the user.
     
  • char = input("Enter a character to replace spaces: ") takes the replacement character.
     

Print Modified String: The function is called, and the modified string is displayed.

 

Program:

def replace_space(string, char):

    return string.replace(" ", char)

string = input("Enter a string: ")

char = input("Enter a character to replace spaces: ")

print("Modified string:", replace_space(string, char))