• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.
    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python usage of format --version2 of Python

tree123

New Coder
Python:
    url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
    for pageNum in range(1,3):
        new_url = format(url%pageNum)

Hello,

The quoted code is from a tutorial. And I am learning by myself. The purpose of the lines is about getting all pictures in different webpages from a website via internet spider --Python.

I've known %d is a integer decimal in Line 1;
And someone has told me the usage of format is the version 2 of Python, but he couldn't tell me more about it.

Would someone please tell me the uage of 'format' in Line 3 of the code above?
1. Specifically, what are the parameters in the bracket of the format?
2. Does the first parameter- in this case 'url', stands for the string that I am going to repace?
3. There needn't to use a comma to separate url from %pageNum?
4. I've searched this usage from the Internet, but got nothing. Would you tell me what keywords are for searching it--- the usage of format in version 2, or could you provide me with the relevant links about this? I would like to learn the grammar of 'format'.

Thank you!

PS. English is not my native language. If my words can't be understood, please let me know.
 

Krusty the Senile

Active Coder
I was testing this in repl.it:
Python:
url = 'https://www.qiushibaike.com/pic/page/%d/?s=5184961'
for pageNum in range(1,3):
  new_url = format(url %pageNum)
  print(new_url)

url2 = 'https://www.qiushibaike.com/pic/page/{}/?s=5184961'
for pageNum in range(1,3):
  new_url = url2.format(pageNum)
  print(new_url)

The second version is what I think is python 3 compatible. They both produce the same result. Looks like in python 3 '%' based placeholders are replaced with '{}'. I'm not sure how or why "format" in python 2 is the way it is, but I've never really had a chance to deep dive into python.

References: https://pyformat.info/ https://docs.python.org/3/library/string.html#formatspec
 
Top Bottom