In python how to replace a character in a string

Viewed 119
import re

n=input("Enter a String:")

# Replace the String based on the pattern

replacedText = re.sub('[%]+','$', n,1)

# Print the replaced string

print("Replaced Text:",replacedText)

input I have given is:

ro%hi%

Output:

ro$hi%

I want to change the second % in the String with empty space(''). Is it possible. For that what changes can I do in my code.

4 Answers

Here is an arguably dumb solution, but it seems to do what you need. Would be good if you want to avoid regex and don't mind two function calls (i.e., performance in that sense isn't critical).

input_text = "ro%hi%"

output_text = input_text.replace("%", "$", 1).replace("%", "", 1)

print(output_text)

Terminal output:

$ python exp.py
ro$hi

use replace() function. Specify how many occurances you need to replace at the end.

x = "ro%hi%"
print(x.replace("%", "$", 1)

You can just do n.replace('%','')

You can use .replace("%", "$", 1) which will replace first % with $ then apply another .replace("%", "") to replace second % with ''.

n=input("Enter a String:")

# Print the replaced string
# This will replace the first % with $ and replace second % with ''
print("Replaced Text:",n.replace('%','$',1).replace('%', '', 1))
# If there are only two % in your input then you can use
# print("Replaced Text:",n.replace('%','$',1).rstrip('%')

Output:

ro$hi
Related