Reputation: 399
I am trying to initialize a long string value to a variable, but this string has a word that can not be constant, like this example.
Say I want to store a string like this.
str = "https://stackoverflow.com/users/7833397/meskerem"
But assume the number 7833397 will change over time, so I am trying to find a way to store the string while making making a wildcard for the number. But I am not sure if this can be done in Python
Upvotes: 9
Views: 12859
Reputation: 5945
First, avoid usign the identifier str
. Second, you can put placeholders in strings using two methods of string formatting:
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))
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.
Upvotes: 7
Reputation: 2513
You can use '%s'(string formatting syntax )
modified_str = "https://stackoverflow.com/users/%s/meskerem" % (number,)
Upvotes: 0
Reputation: 1686
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")
Upvotes: 25