Home  >  Article  >  Backend Development  >  Python program to replace spaces in string with specific characters

Python program to replace spaces in string with specific characters

WBOY
WBOYforward
2023-08-25 14:29:072137browse

Python program to replace spaces in string with specific characters

In Python, you can use the replace() method to replace spaces with special characters in a string. The replace method replaces all occurrences of a substring with a new substring. In this article, we will see how to replace the spaces of a string with another specific substring using the replace() method.

Syntax of Replace method

The syntax of the replace method is as follows:

string.replace(old, new[, count])

The replace method accepts two inputs, one is the old string, which is the substring to be replaced, and the other input is the new string, which is the substring to be placed at the position of the old substring, and a count Parameter that specifies the number of occurrences of the old string to be replaced. If no count argument is provided, all occurrences of the old string are replaced with the new string.

Example: Replace spaces with hyphens

To replace spaces in a string with hyphens, we need to pass the old string as a space (' ') and the new string as a hyphen ('-') to the replace() method. In the example below, we have replaced all spaces in the string with hyphens.

s = "Hello World"
s = s.replace(' ', '-')
print(s)

Output

Hello-World

Example 2: Replace spaces with underscores

To replace spaces in a string with underscores, we need to set the old string to spaces (‘ ’) and the new string to underscores (‘_’) in the replace method. The corresponding code is as follows −

s = "This is a sentence."
s = s.replace(' ', '_')
print(s)

Output

This_is_a_sentence.

Example 3: Replace only a limited number of spaces

To replace a limited number of spaces, we need to use the count input when calling the replace method. In the example below, we will replace only the first two spaces in the string with underscores, therefore setting the count value to 2. The code to replace a limited number of spaces with special characters is as follows -

s = "I am learning Python programming."
s = s.replace(' ', '_', 2)
print(s)

Output

I_am_learning Python programming.

in conclusion

In this article, we learned how to replace spaces in a string with special characters using the replace() method. The replace method accepts as input the old string to replace, the new string to replace with, and a count of the number of replacements to perform, and returns the replaced string as output.

The above is the detailed content of Python program to replace spaces in string with specific characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete