1
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.

0

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

1 Comment

How does that answer the question? It gives the exact same output...
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.