You don't need a regular expression for that. I would do
string = "What $noun
verb$?"
print string.replace("$noun$", "the heck")
Only use regular expressions when needed. It's generally slower.
Answer from Ztyx on Stack OverflowYou don't need a regular expression for that. I would do
string = "What $noun
verb$?"
print string.replace("$noun$", "the heck")
Only use regular expressions when needed. It's generally slower.
Given that you are free to modify $noun$ etc. to your liking, best practise to do this nowadays is probably to using the format function on a string:
"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
Find and replace word in a string | Python
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
Replace stringโ words with txt file words
If the file replacements.txt looks like
- word2:replword2 - word4:replword4
then you can build a dictionary from it pretty easily. Here's one way to do it.
replacement_words = {}
with open("replacements.txt") as file:
for line in file:
line = line.lstrip("- ").strip()
word, replacement = line.split(":")
replacement_words[word] = replacement
print(replacement_words)
my_string = "word1 word2 word3 word4"
print(my_string)
for word, replacement in replacement_words.items():
my_string = my_string.replace(word, replacement)
print(my_string)If your replacement file doesn't have to look like that, you could put it in a standardized form. For example, JSON.
{
"word2": "replword2",
"word4": "replword4"
}Then the parsing part can be handled by a library.
from json import load
with open("replacements.json") as file:
replacement_words = load(file)
print(replacement_words)
my_string = "word1 word2 word3 word4"
print(my_string)
for word, replacement in replacement_words.items():
my_string = my_string.replace(word, replacement)
print(my_string) More on reddit.com How to find exact match in vi editor?
Hello,
I'm given a string and an list like this.
String: "This is my name {{1}} and last name as {{2}} and company name as {{3}}"
List: ['Foo', 'Bar', 'myCompany']
I want to replace all the words enclosed in double curly parenthesis {{X}} by the value in list. It should become like this.
Result: "This is my name Foo and last name as Bar and company name as myCompany"
How to go about it? Can it be done with regex?
word1 = input("Word: ") # lets say that the given word is "tower"
word2 = "********************"
word2 = word2.replace(word[3], word[3])
print(word2)
# Now the my code replaces all the "*" characters with the character "e"
# It just prints "eeeeeeeeeeeeeeeeeeee"
# I would like the code only to replace the 4th character with the other strings 4th
# I'd like it to print "***e****************"