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())

代码用来实现对中国天气网的天气状况的抓取,并利用正则表达式对抓取下来的字符串信息进行操作,获得所需的信息,但是输出结果却是:这里写图片描述
可以看到气温一栏并没有成功输出,但是后面再次重新打print却又成功输出,查阅网上资料发现str.format()前面只能是字符串,而不可以是字符串和变量组合起来的东西,哪怕变量是字符串也不行,换句话说,也就是format前面的必须是在引号里面,方才可以成功输出,否则就会出现把{}输出的结果。
总结而言,也就是说,如果要使用.format输出,就得把变量全部放到format中,前面是一个引号中的字符串。要么就干脆用字符串的连接符合%d,%s等方式输出。
注:后又经过尝试发现实际上实际上%s,%d等输出与.format是相同的,都是前面是一个str,且在一个引号里面,要么全部都用字符串连接符等输出。

`

猜你喜欢

转载自blog.csdn.net/qq_39805362/article/details/82254174