Use the format method.
template = "https://stackoverflow.com/users/{0}/meskerem"
# Lots of stuff happens here
url = template.format("7833397")
The format method supports its own little mini language, and depending on your use-case you may find it more intuitive to name the various parts of your template, too:
template = "https://stackoverflow.com/users/{id}/{username}"
# Lots of stuff happens here
url = template.format(id="7833397", username="meskerem")
Answer from ymbirtt on Stack OverflowIs it possible to declare a variable with a value for string and a placeholder in python? - Stack Overflow
python - string.format() with optional placeholders - Stack Overflow
Placeholder text on input not showing
Why use %s if you can use variables for placeholders?
Videos
Use the format method.
template = "https://stackoverflow.com/users/{0}/meskerem"
# Lots of stuff happens here
url = template.format("7833397")
The format method supports its own little mini language, and depending on your use-case you may find it more intuitive to name the various parts of your template, too:
template = "https://stackoverflow.com/users/{id}/{username}"
# Lots of stuff happens here
url = template.format(id="7833397", username="meskerem")
First, avoid usign the identifier str. Second, you can put placeholders in strings using two methods of string formatting:
Old style
The "old" style uses C-style string formatting syntax, and "modulo" operation on the string to do the actual insertion. You can pass multiple replacements as a tuple:
s = "foo%sbaz" # expects a string
print(s%"bar")
s2 = "foo%s%d"
print(s2%("bar", 2))
New style
The "new" style uses a generic {} which can be filled using the str.format() method. Multiple replacements are passed as a unzipped tuple, i.e. as mutiple arguments:
s = "foo{}baz" # can be "anything"
print(s.format("bar"))
s2 = "foo{}{}"
print(s2.format("bar", 2))
This site might come handy as a reference.
Here is one option:
from collections import defaultdict
my_csv = '{d[first]},{d[middle]},{d[last]}'
print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) )
"It does{cond} contain the the thing.".format(cond="" if condition else " not")
Thought I'd add this because it's been a feature since the question was asked, the question still pops up early in google results, and this method is built directly into the python syntax (no imports or custom classes required). It's a simple shortcut conditional statement. They're intuitive to read (when kept simple) and it's often helpful that they short-circuit.