天天看點

python3中的.format()輸出問題

今天使用PYTHON的format進行輸出,結果遇到了無法成功輸出的問題,感到十分奇怪,見下所示:

# -*- coding: utf-8 -*

from urllib import request
import requests
import json
from bs4 import BeautifulSoup
import re


url1 = 'http://flash.weather.com.cn/wmaps/xml/china.xml'  #擷取全國幾千個縣以上機關的城市代碼
url2 = 'http://mobile.weather.com.cn/js/citylist.xml'   #一次性擷取全國+國外主要城市,8763個城市清單資訊。
try:
    r=requests.get(url1)       #連接配接url并打開
    sta=r.status_code          #傳回狀态
    if sta == 200:
        print("連接配接中國天氣網成功")
except:
    print("連接配接中國天氣網請求失敗")
else:
    r.encoding='utf-8'
    text1 = (r.text)
    #print(type(text1))
    #print(text1)
    weather_info = text1.split('\r\n')
    #print(weather_info)
    #html = request.urlopen(url1).read().decode('utf-8')
    #print("輸出urlopen函數得到的内容:")
    #print(html)
    #print(type(html))
    #if html == text1:
        #print("the same function")
    
    still = 1
    while still>0:
        print("請輸入城市名字:")
        cityname = input()
        for index in range(len(weather_info)):
            qu = re.search(r'.*city quName=(.*) .*',weather_info[index], re.M|re.I)
            if qu:
                city = re.search(r'.*cityname="(.*?)".*',weather_info[index], re.M|re.I)
                if city:
                #print(city.group(1))
                    if city.group(1) == cityname:
                        wea_info1 = re.search(r'.*city quName="(.*?)" .*',weather_info[index], re.M|re.I)
                        wea_info2 = re.search(r'.*cityname="(.*?)" .*',weather_info[index], re.M|re.I)
                        wea_info3 = re.search(r'.*stateDetailed="(.*?)" .*',weather_info[index], re.M|re.I)
                        wea_info4 = re.search(r'.*tem1="(.*?)" .*',weather_info[index], re.M|re.I)
                        wea_info5 = re.search(r'.*tem2="(.*?)" .*',weather_info[index], re.M|re.I)
                        wea_info6 = re.search(r'.*windState="(.*?)".*', weather_info[index], re.M | re.I)
                        print(type(wea_info4.group(1)))
                        print(wea_info5.group(1))
                        print(" 城市:"+wea_info1.group(1)+wea_info2.group(1)+'\n'+"天氣狀況:"+wea_info3.group(1)+'\n'+'氣溫:{0}-{1}\n'+"風力狀況:"+wea_info6.group(1)+'\n'.format(wea_info5.group(1),wea_info4.group(1)))
                        print("氣溫:{0}-{1}\n".format(wea_info5.group(1),wea_info4.group(1)))
                        break
        else:
            #print("not found")
            print("sorry,city not found")
        print("是否希望繼續查詢?")
        print("是,輸入1\n否,輸入0")
        still = int(input())
           

代碼用來實作對中國天氣網的天氣狀況的抓取,并利用正規表達式對抓取下來的字元串資訊進行操作,獲得所需的資訊,但是輸出結果卻是:

python3中的.format()輸出問題

可以看到氣溫一欄并沒有成功輸出,但是後面再次重新打print卻又成功輸出,查閱網上資料發現str.format()前面隻能是字元串,而不可以是字元串和變量組合起來的東西,哪怕變量是字元串也不行,換句話說,也就是format前面的必須是在引号裡面,方才可以成功輸出,否則就會出現把{}輸出的結果。

總結而言,也就是說,如果要使用.format輸出,就得把變量全部放到format中,前面是一個引号中的字元串。要麼就幹脆用字元串的連接配接符合%d,%s等方式輸出。

注:後又經過嘗試發現實際上實際上%s,%d等輸出與.format是相同的,都是前面是一個str,且在一個引号裡面,要麼全部都用字元串連接配接符等輸出。