我试图将一个长字符串值初始化为一个变量,但是这个字符串有一个不能是常量的词,就像这个例子。
假设我想像这样存储一个字符串。
str = "https://stackoverflow.com/users/7833397/meskerem"
但假设数字 7833397 会随时间变化,所以我试图找到一种方法来存储字符串,同时为该数字制作通配符。但是我不确定这是否可以在 Python 中完成
请您参考如下方法:
使用 format方法。
template = "https://stackoverflow.com/users/{0}/meskerem"
# Lots of stuff happens here
url = template.format("7833397")
format 方法支持它自己的小型迷你语言,并且根据您的用例,您可能会发现命名模板的各个部分也更直观:
template = "https://stackoverflow.com/users/{id}/{username}"
# Lots of stuff happens here
url = template.format(id="7833397", username="meskerem")
