Reputation:
I am fairly new to Python, teaching it to myself by watching tutorials and doing the trial and error kind of thing, and I ran into a task, which I am not able to solve right now:
I am reading from a file with following code:
def read_file(file):
try:
with open(file) as f:
content = f.read()
return content
except FileNotFoundError:
print("\nThis file does not exist!")
exit()
The file(.txt) I am reading contains a text with multiple placeholders:
Hello {name}, you are on {street_name}!
Now I want to replace the placeholders {name}
and {street_name}
with their corresponding variables.
I know how f-strings work. Can this somehow be applied to this problem too, or do I have to parse the text to find the placeholders and somehow find out the fitting variable that way?
Each text I read, contains different placeholders. So I have to find out, which placeholder it is and replace it with the according string.
Upvotes: 2
Views: 923
Reputation: 1
Here is a solution similar to that proposed by @Timus, but completely avoiding regular expressions.
This works in case you have a dictionary of known placeholders, and want to use it with an input text containing unknown placeholders that are to be replaced with a default text.
from collections import defaultdict
input_string = "The quick {color} fox {action} over the {adjective} dog."
placeholders = defaultdict(
lambda: "UNKNOWN",
color='brown',
action='jumps',
animal='fox'
)
print(input_string.format_map(placeholders))
#>> The quick brown fox jumps over the UNKNOWN dog.
Upvotes: 0
Reputation: 11321
Not sure if that is what you are looking for:
string = "Hello {name}, you are on {street_name}!"
string = string.format(name="Joe", street_name="Main Street")
print(string)
or
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
string = string.format(name=name, street_name=street_name)
print(string)
gives you
Hello Joe, you are on Main Street!
See here.
If you actually don't know what placeholders are in the text then you could do something like:
import re
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
placeholders = set(re.findall(r"{(\w+)}", string))
string = string.format_map({
placeholder: globals().get(placeholder, "UNKOWN")
for placeholder in placeholders
})
If you know that all placeholders are present as variables, then you could simply do:
string = "Hello {name}, you are on {street_name}!"
name = "Joe"
street_name = "Main Street"
string = string.format_map(globals())
Upvotes: 2