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?
CodePudding user response:
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 = re.findall(r"{(\w )}", string)
string = string.format_map({
placeholder: globals().get(placeholder, "UNKOWN")
for placeholder in placeholders
})
CodePudding user response:
If you know statically the name of your variables you can do as in this issue.
- Read your file
- Call
str.replace()
on the string you just got with your placeholder and the variable you want to inject in - Overwrite your file with the substituted string
However if you don't know the name of your variables, you would have to dynamically evaluate the placeholders in the text file and that would be a big security issue.