python string.format()方法

方法源码:

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

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

例子:

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

输出:

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

猜你喜欢

转载自blog.csdn.net/smh2208/article/details/80686655