I was working on a project and encountered an interesting situation. I'm reading some data from a file and use them to format/complete a string like this.
#After I read the file I create an internal dictionary to use, so for brevity
#I'll use an example of the retrieved data
film = {"name":"Gran Torino", "type":"Drama"}
movie = "{name} is a {genre} movie. The vote given by {person} is {stars}"
movie = movie.format(name=film["name"],genre=film["type"])
This obviously generate an error, this one:
Traceback (most recent call last):
File "movie.py", line 65, in <module>
movie = movie.format(name=film["name"],genere=film["type"])
KeyError: 'person'
because some keys are missing.
The missing one will be retrieved from user when he will input them.
I already know some way to evade the error, like format everything after I retrieved the other data from the user input.
However, I'm curious about something:
Is there a way in Python, using .format()/f-strings/string Template, for formatting a string with some initial value and maintain some missed places a later second passage? In other words can I insert only certain value and later the missing one?
Pseudo-code of what I try to achieve
string = "{first} text {second} ... and so on {last}"
#apply one time format but only one some place-holders
result = string.format(first=value) #dosen't need to generate an error
print(result) # "value text {second} ... and so on {last}"
Like you can see what I want is to know if in the language there is a way of doing this procedure with the built-in formatting options and without create a new function for this.
Side note:
I already tried to use some other options like string Template but wasn't able to make it work. Moreover, I know that is possible first concatenate the data in my possession, later add a string part and format later like this:
first_part = film["name"] + " is a " + film["genre"] + " movie."
second_part = "The vote given by {person} is {stars}"
movie = first_part + second_part
#later when I have stars and person
movie.format(person=v1,stars=v2)
This works, but I would love to understand if I can use two times format() method instead.