python string.format()方法

清疚 2022-05-22 03:25 296阅读 0赞

方法源码:

  1. def format(self, *args, **kwargs): # known special case of str.format
  2. """
  3. S.format(*args, **kwargs) -> str
  4. Return a formatted version of S, using substitutions from args and kwargs.
  5. The substitutions are identified by braces ('{' and '}').
  6. """
  7. pass

根据源码可知,该方法用参数代替string里一部分并返回代替后的结果。

例子:

  1. start_url = 'http://baidu.com/{}.html'
  2. urls = [start_url.format(page) for page in range(0,4)]
  3. for url in urls:
  4. print(url)

输出:

http://www.baidu.com/0.html
http://www.baidu.com/1.html
http://www.baidu.com/2.html
http://www.baidu.com/3.html

发表评论

表情:
评论列表 (有 0 条评论,296人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python字典方法

    就像其他内建类型一样,字典也有方法。这些方法非常有用,但是可能不会像列表或者字符串方法那样被频繁使用,以下是一些具体的方法。 1.clear方法 clear方法