day7:字符格式化输出,数据类型,for循环,break,continue,标志位

一、字符格式化输出

 占位符 %s s = string

      %d  d = digit 整数

      %f  f = float 浮点数,约等于小数

Ctrl+问好  整段注释

在命令窗口输入  exit(),退出当前运算,进入初始盘符。

Chcp 936 在命令窗口改字符编码。

如果不采用格式化输出,写一个用户交互程序

name = input("Name:")
age = int(input("Age:"))
job = input("Job:")
salary = input("Salary:")

if salary.isdigit():  # 判断长的是否像数字
    salary = int(salary)
else:
    # print("must input digit")
    exit("must input digit")  # 退出程序

print(name, age, job, salary)

采用格式化输出为:

name = input("Name:")
age = int(input("Age:"))
job = input("Job:")
salary = input("Salary:")


if salary.isdigit():  # 判断长的是否像数字
    salary = int(salary)
else:
    # print("must input digit")
    exit("must input digit")  # 退出程序

# print(name, age, job, salary)


msg = '''
------------- info of %s ----------------
Name:%s
Age:%s
Job:%s
Salary:%s
You will be retired in %s years
--------------- end -------------
''' % (name, name, age, job, salary, 65-age)

print(msg)

二、数据类型初识

   1. 数字

       1.1 整数  int(integer)   整型(int)  长整型(longint)

       in python3 已经不区分整型与长整型,统一都叫整型

       in C语言里,需要声明,比如 int age 22 , long age

      1.2  float(浮点型)

      1.3  复数

      1.4  布尔 只有2种状态,分别是  真 True    假 False

           salary.isdigit()

           计算机中, 一切皆为对象

           世界万物,皆为对象,一切对象皆可分类

2.字符串拼接

2.1 创建字符串

var1 = 'hello world!'
var2 = 'python RAlvin'

对应操作

#1 重复输出字符串

print('hello'*2)
#2 [] , [:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的
print('helloworld'[2:])
#3 in 成员运算符 - 如果字符串中包含给定的字符返回 True

print('el' in 'hello')
print(123 in [23, 45, 123])#列表

#4 % 格式字符串

print('%s is a good teacher' % 'alex')
# 5  +  字符串拼接
a = '123'
b = 'abc'
print(a+b)
a = '123'
b = 'abc'

c = ''.join([a, b])
print(c)
a = '123'
b = 'abc'

c = '----'.join([a, b])
print(c)#123----abc

python的内置方法

#string的内置方法

st = 'hellokitty'
st.count('l')
print(st.count('l'))# l的个数 2
print(st.capitalize())#Hellokitty
print(st.center(50, '-'))  # --------------------hellokitty--------------------
print(st.encode())
print(st.endswith('ty'))#以某个字符串结尾,有返回值
print(st.startswith('he'))#判断是否以某个内容开始
st = 'he\tllokitty'
print(st.expandtabs(tabsize=10))
st = 'hellokitty'
print(st.find('t'))# 查找到第一个元素,并将索引值返回
st = 'hellokitty {name} is {age}'
print(st.format(name='alex', age=37))
print(st.format_map({'name': 'alex', 'age': 37}))
st = 'hellokitty {name} is {age}'
print('abc456'.isalnum())
print('AF00'.isdecimal())
print('1234'.isdigit())#true
print('1234.99'.isdigit())#false
print('1234.99uu'.isnumeric())
print('34abc'.isidentifier())#false 判断非法字符
print('Abc'.islower())#只要有一个大写,就false
print('Abc'.isupper())#只要有一个小写,就false
print(' e'.isspace())#判断是否是空格
print('My Title '.istitle())#每个单词的首写字母  要大写
print('My Title '.lower())#大写变小写
print('My Title '.upper())#所有变大写
print('My Title '.swapcase())#大写变小写,小写变大写
print('My Title '.ljust(50, '*'))#只在左面
print('My Title '.rjust(50, '*'))#只在右面
print('   My Title\n'.strip())#去掉空格  也可以去掉\t  \n
print('ok')
print('My Title '.lstrip())#
print('My Title '.rstrip())#
print('My Title '.replace('Title', 'lesson'))#
print('My Title Title '.replace('Title', 'lesson'))#
print('My Title Title '.replace('Title', 'lesson', 1))#
print('My Title '.rfind('t'))
print('My Title Title'.split(' '))
print('My Title Title'.split('i'))#以什么为分割对象
print('My Title Title'.split('i', 1))#以什么为分割对象
print('My Title Title'.rsplit('i', 1))#之分割一次,以右为准
print('My title Title'.title())#变成标题

一些重要的字符串内置方法  在上述标红了

程序: 三级菜单

要求:

1.打印省、市、县三级菜单

2.可返回上一级

3.可随时退出程序

menu = {
    '北京': {
        '朝阳': {
            '国贸': {

                'CICC': {},
                'HP': {},
                '工商银行': {},
                'CCTV': {}

            },
            '望京': {
                '陌陌': {},
                '奔驰': {},
                '360': {}
            },
            '三里屯': {
                'youyiku': {},
                'apple': {}

            }

        },

        '昌平': {
            '沙河': {
                'old boy': {},
                'ataibaozi': {}
            },
            '天通苑': {
                '链家': {},
                '我爱我家': {}
            },
            '回龙观': {}

        },
        '海淀': {
            '五道口': {
                '谷歌': {},
                '网易': {},
                'sohu': {},
                'sogou': {},
                '快手': {}

            },
            '中关村': {
                'youku': {},
                'iqiyi': {},
                '汽车之家': {},
                '新东方': {},
                'qq': {}

            }
        }


    },
    '上海': {
        '浦东': {
            '陆家嘴': {
                'CICC': {},
                '高盛': {},
                '摩根': {}
            }
        },
        '闵行': {},
        '静安': {}

    },
    '山东': {
        '济南': {},
        '德州': {
            '乐陵': {
                '丁务镇': {},
                '城区': {}
            },
            '平原': {}
        }


    }
}

back_flag = False
exit_flag = False

while not back_flag and not exit_flag:
    for key in menu:
        print(key)

    choice = input('1>>:'). strip()
    if choice == 'q':
        exit_flag = True
    if choice in menu:
        while not back_flag and not exit_flag: #让程序停在第二层
            for key2 in menu[choice]:
                print(key2)


            choice2 = input('2>>:').strip()
            if choice2 == 'b':
                back_flag = True
            if choice2 == 'q':
                exit_flag = True
            if choice2 in menu[choice]:
                while not back_flag and not exit_flag:
                    for key3 in menu[choice][choice2]:
                        print(key3)



                    choice3 = input('3>>:').strip()
                    if choice3 == 'b':
                        back_flag = True
                    if choice3 == 'q':
                        exit_flag = True

                    if choice3 in menu[choice][choice2]:
                        while not back_flag and not exit_flag:
                            for key4 in menu[choice][choice2][choice3]:
                                print(key4)

                            choice4 = input('4>>:').strip()
                            print('last level')
                            if choice4 == 'b':
                                back_flag = True
                            if choice4 == 'q':
                                exit_flag = True
                        else:
                            back_flag = False
                else:
                    back_flag = False

        else:
            back_flag = False

改进版本

menu = {
    '北京': {
        '朝阳': {
            '国贸': {

                'CICC': {},
                'HP': {},
                '工商银行': {},
                'CCTV': {}

            },
            '望京': {
                '陌陌': {},
                '奔驰': {},
                '360': {}
            },
            '三里屯': {
                'youyiku': {},
                'apple': {}

            }

        },

        '昌平': {
            '沙河': {
                'old boy': {},
                'ataibaozi': {}
            },
            '天通苑': {
                '链家': {},
                '我爱我家': {}
            },
            '回龙观': {}

        },
        '海淀': {
            '五道口': {
                '谷歌': {},
                '网易': {},
                'sohu': {},
                'sogou': {},
                '快手': {}

            },
            '中关村': {
                'youku': {},
                'iqiyi': {},
                '汽车之家': {},
                '新东方': {},
                'qq': {}

            }
        }


    },
    '上海': {
        '浦东': {
            '陆家嘴': {
                'CICC': {},
                '高盛': {},
                '摩根': {}
            }
        },
        '闵行': {},
        '静安': {}

    },
    '山东': {
        '济南': {},
        '德州': {
            '乐陵': {
                '丁务镇': {},
                '城区': {}
            },
            '平原': {}
        }


    }
}

current_layer = menu
# parent_layer = menu

parent_layers = []  #保存所有父级,最后一个元素永远都是父亲级

while True:
    for key in current_layer:
        print(key)

    choice = input('>>:').strip()

    if len(choice) == 0:
        continue

    if choice in current_layer:
        # parent_layer = current_layer  #改之前相当于父亲
        parent_layers.append(current_layer)#在进入下一层之前,把当前层(也就是下一层父级)追加到列表中,下一次
        #loop,当用户选择b,就可以直接取列表的最后一个值出来就可以
        current_layer = current_layer[choice]

    elif choice == 'b':
        # current_layer = parent_layer  #把子层改为父亲层
        if parent_layers:
            current_layer = parent_layers.pop()#去除列表的最后一个值,因为它就是当前层的父级

    else:
        print('无此项')

Name = Alex

Age = 22

Print(“my name is %s“ %name)#字符串格式化输出(最好用这个)

或者print”my name is %s”%name

Print(“my name is”,name,”and I am ”,age, ”yearsold”)#逗号拼接

Print(“my name is”+name+”and I am ”+age+”years old”)#加号拼接

但是经常不这样用,效率低,用加号相当于计算机开辟了5快内存

3.列表和元组

3.1列表

列表的增删改查操作

a = ['wuchao', 'xiaoli', 'sanpang', 'ligang', 'jinxing']
# print(a)
# #增删改查
# #查   切片  取值范围左包括右不包括
# #如果想取到最后一个值,在不知道元素个数的情况下,冒号后什么也不加
# print(a[1:4])
#
# print(a[1:])
# print((a[1:-1]))#取到最后一项的前一项
#
# #跳着取
# print(a[1:-1:1])#从左到右 一个一个取
# print(a[1:-1:2])#从左到右 隔一个取
# print(a[1::2])
# print(a[3::-2])
# #print(a[1:-1:-2]) 这个是错的  既然从右往左走,需要从右边的元素开始取
# b = a[3::-1]
# print(b)
# print(a[-2::-1])

#增 append insert
#a.append('xuepeng')#默认插到最后一个位置
#print(a)
# a.insert(1, 'xuepeng')#将数据插入到任意一个位置
# print(a)

#改
# a[1] = 'yinxing'
# print(a)
# a[1:3] = ['a', 'b']
# print(a)


#删  remove pop  del
# a.remove('wuchao')#== a.remove(a[0])  只是删除具体的内容  只是作为一个整体进行去删
# print(a)

# a.pop(1)
# b = a.pop(1)#pop是按照索引删除,比remove多了一个return值功能
# print(a)
# print(b)

# del a[0]
# print(a)
# del a
# print(a)#运行结果会出错

列表的另外一种操作方法

a = list((1, 2, 3))
print(a)

其他操作  

1.count  的操作

t = ['to', 'be', 'or', 'not', 'to', 'be']. count('to')
print(t)

2.extend操作

#extend
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
print(b)

3.index操作

a = ['wuchao', 'xiaoli', 'sanpang', 'ligang',  'jinxing']
print(a.index('xiaoli'))

若a里有两个重复的名字 则 可以采用切片的方法

a = ['wuchao', 'xiaoli', 'sanpang', 'ligang', 'xiaoli', 'jinxing']
first_xl_index = a.index('xiaoli')
print('first_xl_index', first_xl_index)
little_list = a[first_xl_index+1:]
second_xl_index = little_list.index('xiaoli')
print('second_xl_index', second_xl_index)
xl_index_a = first_xl_index + second_xl_index+1
print(xl_index_a)

4.reverse 颠倒  没有返回值

#reverse
a = ['wuchao', 'xiaoli', 'sanpang', 'ligang', 'xiaoli', 'jinxing']
a.reverse()
print(a)

5.sort排序  没有返回值(默认从小往大排)

x = [4, 6, 2, 1, 7, 9]
x.sort()
print(x)

从大往小排

x = [4, 6, 2, 1, 7, 9]
x.sort(reverse=True)
print(x)

作业  购物车程序

product_list = [
    ('mac', 9000),
    ('kindle', 800),
    ('car', 9000000),
    ('book', 105),
    ('bike', 2000)
]
saving = input('please input your saving money:')
shopping_car = []

if saving.isdigit():
    saving = int(saving)
    while True:

    # print(product_list)
    # for i in product_list:
    #     print(i)
    #     print(product_list.index(i), i)

    # for i in enumerate(product_list):
    #     print(i)
    # for i in enumerate(product_list, 1):
    #     print(i)
    #打印商品
        for i, v in enumerate(product_list, 1):
            print(i, '>>', v)
        # 引导用户选择商品
        choice = input('选择购买商品编号[退出:q]:')
        # 验证输入是否合法
        if choice.isdigit():
            choice = int(choice)
            if choice > 0 and choice <= len(product_list):
                # 将用户选择商品通过choice取出来
                p_item = product_list[choice-1]
                # 如果钱够,用本金减去商品价格,并把商品放入购物车
                if p_item[1] < saving:
                    saving -= p_item[1]
                    shopping_car.append(p_item)
                else:
                    print('余额不足,还剩%s' % saving)

                print(p_item)
            else:
                print('编码不存在')

        elif choice == 'q':
            print('-------您已经购买如下商品----------')
            # 循环遍历购物车的商品,购物车存放的是已买商品
            for i in shopping_car:
                print(i)
            print('你还剩%s元钱' % saving)
            break
else:
    print('invalid input')

3.2元组

a, b = [2,3]
print(a)
print(b)

简单的赋值操作,输出结果

2

3

4.字典

字典是python中唯一的映射类型,采用键值形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如数字,字符串,元组。

字典是除列表外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。二着之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。


可以看出a的内存地址

创建字典:

字符串存取

dic = {'name': 'Alex', 'Age': '35', 'hobby': 'girl', 'is handsome': True}
print(dic)
print(dic['name'])

整型存取

dic = {1: 'Alex', 'Age': '35', 'hobby': 'girl', 'is handsome': True}
print(dic)
print(dic[1])

键是不可变类型,运行出错

dic = {[1, 2]: 'Alex', 'Age': '35', 'hobby': {'girl_name': '铁锤', 'Age': '45'}, 'is handsome': True}

print(dic['hobby'])
值 可以是可变的
dic = {1: 'Alex', 'Age': '35', 'hobby': {'girl_name': '铁锤', 'Age': '45'}, 'is handsome': True}

print(dic['hobby'])

字典的另外一种创建方式

dic1 = dict((('name', 'Alex'),))
print(dic1)
dic1 = dict([['name', 'Alex'],])
print(dic1)

注意:对括号要求不太高

字典的另外一种创建方式

dic6 = dict.fromkeys(['host1', 'host2', 'host3'], 'text')
print(dic6)  # {'host3': 'text', 'host2': 'text', 'host1': 'text'}

dic6['host2'] = 'abc'
print(dic6)  # {'host3': 'text', 'host1': 'text', 'host2': 'abc'}
dic6 = dict.fromkeys(['host1', 'host2', 'host3'], ['text1', 'text2'])
print(dic6)  # {'host2': ['text1', 'text2'], 'host1': ['text1', 'text2'], 'host3': ['text1', 'text2']}

dic6['host2'][1] = 'text3'
print(dic6)  # {'host3': ['text1', 'text3'], 'host2': ['text1', 'text3'], 'host1': ['text1', 'text3']}

字典的操作

1.增

dic1 = {'name': 'Alex'}
dic1['Age'] = 18
print(dic1)
dic1 = {'name': 'Alex'}
dic1['name'] = 18
print(dic1)

dic.setdefault 函数 如果字典里有,不动,如果字典里没有,添加上去

dic1 = {'name': 'Alex'}
dic1['age'] = 18
print(dic1)

dic1.setdefault('age', 34)
print(dic1)
dic1 = {'name': 'Alex'}
dic1['age'] = 18
print(dic1)

dic1.setdefault('hobby', 'girl')
print(dic1)

注意dic.setdefault 函数的返回值

dic1 = {'name': 'Alex'}
dic1['age'] = 18
print(dic1)

ret = dic1.setdefault('age', '34')
print(ret)

ret2 = dic1.setdefault('hobby', 'girl')
print(dic1)
print(ret2)

2.查

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
print(dic3['name'])
print(dic3.keys())
print(type(dic3.keys()))
运行结果Alex
dict_keys(['age', 'name', 'hobby'])
<class 'dict_keys'>

可以对其进行转化为列表形式

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
print(dic3['name'])
print(dic3.keys())
print(type(dic3.keys()))
print(list(dic3.keys()))

拿取值和键值对

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
print(dic3['name'])
print(dic3.keys())
print(type(dic3.keys()))
print(list(dic3.keys()))
print(list(dic3.values()))# 拿取值
print(list(dic3.items()))# 拿取键值对

3.改

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
# dic3['name'] = 'alvin'
# # print(dic3)
dic4 = {'sex': 'male', 'hobby': 'girl', 'age': 36}
dic3.update(dic4)
print(dic3)
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
dic4 = {'1': '111', 'name': '222'}
dic3.update(dic4)
print(dic3)

4.删

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
del dic3['name']#删掉的是键值对
print(dic3)
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
dic3.clear()
print(dic3)
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
# dic3.clear()#清空字典
print(dic3.pop('age'))# 有返回值
print(dic3)
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
# dic3.clear()
a = dic3.popitem()#随机删除一个键值对
print(a, dic3)
dic6 = dict.fromkeys(['host1', 'host2', 'host3'], 'text')
print(dic6)  # {'host3': 'text', 'host2': 'text', 'host1': 'text'}

字典的其他操作

5.d.copy() 对字典d进行浅复制,返回一个和d有相同键值对的新字典

6.字典的嵌套

av_catalog = {
    '欧美': {
        'www.youporn.com': ['很多免费的,世界最大的', '质量一般'],
        'www.pornhub.com': ['很多免费的,也很大', '质量比youporn高点'],
        'letmedothistoyou.com': ['多是自拍,高质量图片很多', '资源不多,更新慢'],
        'x-art.com': ['质量很高,真的很高', '全部收费,屌丝请绕过']

    },
    '日韩': {
        'tokyo-hot': ['质量怎样不清楚,个人已经不喜欢日韩范了', '听说是收费的']

    },
    '大陆': {
        '1024': ['全部免费,真好,好人一生平安', '服务器在国外,慢']

    }

}

av_catalog['大陆']['1024'][1] += ',可以用爬虫爬下来'
print(av_catalog['大陆']['1024'])
#  output
['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

7.sorted(dict):返回一个有序的包含字典所有key的列表

dic = {5: '555', 2: '222', 4: '444'}

print(sorted(dic))#[2, 4, 5]
print(sorted(dic.values()))#['222', '444', '555']
print(sorted(dic.items()))#[(2, '222'), (4, '444'), (5, '555')]

8.遍历

dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
# for i in dic3:
#    # print(i)  #默认打印键
#     print(i, dic3[i])# 推荐用这种方式,效率高
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
# for i in dic3.items():
#     print(i)
dic3 = {'age': 18, 'name': 'Alex', 'hobby': 'girl'}
for i, v in dic3.items():
    print(i,v)

还用我们上面的例子,存取这个班学生的信息,如果通过字典来完成

dic = {'zhangsan': {'age': 23, 'sex': 'male'},
       '李四': {'age': 33, 'sex': 'male'},
       'wangwu': {'age': 27, 'sex': 'female'}

}
print(dic)

不可变类型:整型,字符串,元组

可变类型:列表,字典

程序员最忌讳的事情:写重复代码

三、循环loop

    有限循环 ,次数限制

    无限循环=死循环

   continue 结束本次循环,继续下一次循环

    break跳出整个当前的循环

下面是for循环举例

# for i in range(1, 101):
#     if i % 2 == 1:
#         print("loop:", i)

# for i in range(1, 101, 2):
#     print("loop:", i)

# for i in range(100):
#     if i < 50 or i > 70:
#         print(i)

用for循环加break语句 写一个用户登录程序

_user = "majinghui"
_password = "123"

for i in range(3):
    username = input("Username:")
    password = input("Password:")

    if username == _user and password == _password:
        print("welcome %s login..." % username)
        break  # 跳出,循环,中断
    else:
        print("invalid username or password")

上式程序,如果3次用户都输入错误,就不完美,所以如果3次都输入错误,给出输出提示,如下(采用标志位)

_user = "majinghui"
_password = "123"
passed_authentication = False

for i in range(3):
    username = input("Username:")
    password = input("Password:")

    if username == _user and password == _password:
        print("welcome %s login..." % username)
        passed_authentication = True  # 真,成立
        break  # 跳出,循环,中断
    else:
        print("invalid username or password")
if not passed_authentication:
    print("要不要脸,臭流氓")

上个程序也可以更简洁,如下:

_user = "majinghui"
_password = "123"
# passed_authentication = False

for i in range(3):
    username = input("Username:")
    password = input("Password:")

    if username == _user and password == _password:
        print("welcome %s login..." % username)
        # passed_authentication = True   # 真,成立
        break  # 跳出,循环,中断
    else:
        print("invalid username or password")
# if not passed_authentication:
else:
    print("要不要脸,臭流氓")

只要上面的for循环正常执行完毕,中间没被打断,就会执行else语句。break for过后,就不会执行最后面的else语句,在Python里,for后面可以跟else,但不能跟elif。

2.无限循环

while True:
    print("当山峰没有棱角的时候")

上述程序改为有限循环

counter = 0
while True:
    if counter > 2**3:
        break
    counter += 1
    print("当山峰没有棱角的时候")

用while创建用户登陆程序

_user = "majinghui"
_password = "123"
# passed_authentication = False
counter = 0

while counter < 3:
    username = input("Username:")
    password = input("Password:")

    if username == _user and password == _password:
        print("welcome %s login..." % username)
        # passed_authentication = True   # 真,成立
        break  # 跳出,循环,中断
    else:
        print("invalid username or password")
# if not passed_authentication:
    counter += 1
else:
    print("要不要脸,臭流氓")

上述程序继续改进

_user = "majinghui"
_password = "123"
# passed_authentication = False
counter = 0

while counter < 3:
    username = input("Username:")
    password = input("Password:")

    if username == _user and password == _password:
        print("welcome %s login..." % username)
        # passed_authentication = True   # 真,成立
        break  # 跳出,循环,中断
    else:
        print("invalid username or password")
# if not passed_authentication:
    counter += 1
    if counter == 3:
        keep_going_choice = input("你还想玩吗?[Y/N]")
        if keep_going_choice == "Y":
            counter = 0
else:
    print("要不要脸,臭流氓")
在pycharm每行处单击,可以设置断点,但是在执行时点击如下的调试按钮。

此按钮进行一步一步调试

2.2 continue语句

continue 结束本次循环,继续下一次循环

break 跳出整个当前的循环

for i in range(10):
    if i < 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
for i in range(10):
    if i < 5:
        continue
    print(i)
for i in range(10):
    if i < 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
        if j == 6:
            break
for i in range(10):
    if i < 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
        if j == 6:
            break
    break

标志位退出两层循环

for i in range(10):
    if i < 5:
        continue
    print(i)
    for j in range(10):
        print("layer:", j)
        if j == 6:
            exit_flag = True
            break
    if exit_flag:
        break
    break

四、字符编码

二进制

------->ASCII : 只能存英文和拉丁字符。一个字符占一个字节,8位

--------->gb2312:只能6700多个中文,1980

------------>gbk1.0 : 存了2万多字符,1995

--------------->gb18030:2000,27000中文


----------------->unicode: utf-32:一个字符占 4个字节

----------------->unicode: utf-16:一个字符占 2个字节或2个以上,65535,

----------------->unicode: utf-8:一个英文用ASCII码来存,一个中文占3个字节

in python2 默认是ASCII码

in python3  字符默认unicode,  文件默认编码是utf-8   encode在编码的同时,会把数据转成bytes类型

                                                                                      decode在解码的同时,会把bytes类型转成字符串

b = byte = 字节类型 = 2进制【0-255】

s = 'i am 特斯拉'
s_to_gbk = s.encode('gbk')
print(s_to_gbk)

输出:b'i am \xcc\xd8\xcb\xb9\xc0\xad'


GBK 需要转换为UTF-8格式流程

1、首先通过编码【decode】转换为unicode编码

2、然后通过编码【encode】转换为utf-8的编码

猜你喜欢

转载自blog.csdn.net/MaHilda/article/details/80295336