码迷,mamicode.com
首页 > 其他好文 > 详细

数据类型,字符串,文件处理

时间:2017-09-15 21:41:59      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:变量   case   isl   等级   交换   ima   tuple   其他   for   

数据类型

字符编码

文件处理

 

数据类型

1什么是数据?

x=10.10是我们要存储的数据

2 数据类型

  数字(整形,长整形,浮点型,复数)

  字符串

  字节串:在介绍字符编码时介绍字节bytes类型

  列表

  元组

  字典

集合

 可变or不可变

    !!!可变:值变,id不变。可变==不可hash

    !!!不可变:值变,id就变。不可变==hash

数字类型:

Int:作用:年龄;级别;等级;身份证号等

X=10 #x=int()

Float:作用:

字符串类型

#/usr/bin/env python
# Author:hongjie.gao
# 用途:名字,性别,地址,爱好等  存一个值(特殊之处在于可以把里面的小的字符串取出来),有序的,不可变的
name=‘ghj‘ #name=str(‘ghj‘)
# print(id(name),type(name),name)
# # 按索引取值(正向取,反向取),只能取,不能修改
# print(name[0],type(name[0]))
# print(name[-2],type(name[-2]))
# # 切片(顾头不顾尾,步长)
# print(name[1:2])
#
# GHJ=‘hello world‘
# print(GHJ[1:7])
# print(GHJ[1:7:2])
fhm=‘qlwertyuiop 123‘
# print(fhm[1:13])
# print(fhm[1:13:2])
# print(fhm[1:13:3])
# print(fhm[:])
# print(fhm[::3])
# 倒着取
# print(fhm[::-1])

# 长度
# fhm=‘qlwertyuiop 123‘
# print(len(fhm))

# 成员运算in和 not in
# fhm=‘qlwertyuiop 123‘
# print(‘ 123‘in fhm)
# print(‘1234‘in fhm)
# print(‘ 1234‘not in fhm)

# 移除空白strip:去掉首尾的字符  重点 常用的
# 左:left
# 右:right

password=‘ghj123       ‘
# password=password.strip()
# print(password)
# print(password.strip())

passw = ‘  **123    $$***   ‘
# passw=passw.strip()
# print(passw.strip())
# print(passw.strip(‘*| |$‘))



# 切分split       重点 常用的
user_info=‘name;age;hobbies;sex‘
# print(user_info.split(‘;‘))
# print(user_info.split(‘;‘)[0])
# 默认空格切
# cmd=‘put   a.txt‘
# print(cmd.split()[0])

# file_info=‘put  /a/b/c/d/a.txt‘
# print(file_info.split()[0])
# print(file_info.split(‘/‘,1)[0])

#
# ghj=‘ghj say i have one electric car‘
# print(ghj.split(maxsplit=1))

# ghj=‘ghj_good‘
# print(ghj.endswith(‘good‘))    # 以什么结尾
# print(ghj.startswith(ghj))      # 以什么开头

ghj=‘GHJ sayi have one electric car,my name is GHJ ‘
# print(ghj.replace(‘GHJ‘,‘ghj‘))         #替换,前面old,后面new,默认全替换
# print(ghj.replace(‘GHJ‘,‘ghj‘,1 ))       #替换一次

# print(‘my name is %s,my age is %s‘%(‘ghj‘,25))  # 字符串的格式化
# print(‘my name is {},my age is {}‘.format(‘ghj‘,25))  # 有几个占位符就传几个值
# print(‘{0},{0},{1}‘.format(‘ghj‘,25))   # 花括号里可以控制位置
# print(‘my name is {x},my age is {y}‘.format(y=25,x=‘ghj‘))  #可以不依赖位置传值

# find,rfind,index,rindex,count   了解部分
# find
ghj=‘hello world‘
# print(ghj.find(‘or‘))   # 查找子字符串的起始位置,从左到右找,如果有,则返回第一个子字符串索引
# print(ghj.find(‘dadada‘))   # 查找子字符串的起始位置,从左到右找,如果没有,则返回-1
# rfind  从右往左找
# index
# print(ghj.index(‘or‘))  # 查找子字符串的起始位置,从左到右找,如果有,则返回第一个子字符串索引
# print(ghj.index(‘dadadad‘))      # 查找子字符串的起始位置,从左到右找,如果没有,则报错
# rindex 从右往左找
# count
# print(ghj.count(‘l‘,0,4))  #查找包含子字符串的个数,顾头不顾尾
# print(ghj.count(‘l‘,0,2))

# split        # 把字符串切割成列表  常用操作
user_info=‘name;age;hobbies;sex‘
# l= user_info.split(‘;‘)
# print(l)
#
# # join     # 把列表还原成字符串    常用操作
# print(‘:‘.join(l))
# print(‘‘.join(l))
# print(‘ ‘.join(l))


# center,ljust,rjust,zerofill       常用操作
# ===========ghj============
# print(‘ghj‘.center(30,‘=‘))  #中间对齐,补够30个
# print(‘ghj‘.ljust(30,‘=‘))  #往左对齐,补够30个
# print(‘ghj‘.rjust(30,‘=‘))  #往右对其,补够30个
# print(‘ghj‘.zfill(30))  #直接指定宽度,往右对齐,以0补充,补够30个
#
#  \t 制表符
# ghj=‘abc\t123‘
# print(ghj)   #pycharm默认以一个空格
# print(ghj.expandtabs(3))    #expandtabs指定以几个空格

# ghj=‘ghj Say hello word‘          了解部分
# print(ghj.capitalize())  #首字母大写
# print(ghj.upper())   #全部大写
# print(ghj.lower())  #全部小写
# print(ghj.title())  #每个单词的首字母大写、
# print(ghj.swapcase())   #大小写反转



# is系列
ghj=‘ghj Say hello word‘
# print(ghj.isupper())  #判断是否全部大写
# print(ghj.islower())    #判断是否全部小写
# print(ghj.istitle())    #判断每个单词的首字母是否大写


ghj=‘abc123‘
GHJ=‘dadad‘
print(ghj.isalnum())              #字符串是由字母或数字组成

print(ghj.isalpha())              #字符串是由字母组成
print(GHJ.isalpha())
# ghj=‘  ‘
# print(ghj.isspace())           # 不是重点       #判断是否全是空格,是==ture

# ghj=‘aaaaif123‘
# GHJ=‘aaaaai f123‘
# print(ghj.isidentifier())          # 不是重点   #判断这个字符串里包不包含python的关键字
# print(GHJ.isidentifier())


# 判断数字
# print(ghj.isdigit())      #重点   判断字符串里包含的字符是不是纯数字(bytes,unicode)
# age=25
# ghj=input(‘age>>:‘).strip()  #用户输出的字符串,把空格全部去掉
# if ghj.isdigit():            #判断用户输入的字符串里包含的字符是不是纯数字
#     ghj=int(ghj)             #把字符串转为数字类型
#     if ghj==age:             #
#         print(‘ok‘)          #
# else:
#     print(‘必须输入数字‘)

num1 = b‘4‘  # bytes
num2 = u‘4‘  # unicode,python3中无需加u就是unicode
num3 = ‘四‘  # 中文数字
num4 = ‘壹‘  # 汉字
num5 = ‘Ⅳ‘  # 罗马数字

# print(num1.isdigit())
# print(num2.isdigit())
# print(num3.isdigit())
# print(num4.isdigit())
# print(num5.isdigit())
# isdigit只能判断bytes,unicode类型的数字

# print(num2.isdecimal())
# print(num3.isdecimal())
# print(num4.isdecimal())
# print(num5.isdecimal())
# isdecima只能判断unicode类型

# print(num2.isnumeric())
# print(num3.isnumeric())
# print(num4.isnumeric())
# print(num5.isnumeric())
# snumeric能判断中文数字,罗马数字,汉字数字,银行用

列表类型

#!/use/bin/env python
#Aothor:hongjie.gao
# 可变(id没变,值变),可以存多个值,值可以是任意类型,有序,
#作用:多个装备,多个爱好,多门课程,多个女朋友等

#定义:[]内可以有多个任意类型的值,逗号分隔
# my_girl_friends=[‘yangmi‘,‘liuyifei‘,‘liutou‘,4,5] #本质my_girl_friends=list([...])
# print(my_girl_friends)

# 优先掌握的操作:
# 按索引存取值(正向存取+反向存取):即可存也可以取
# print(my_girl_friends[2])   # 取出第三个女友  正取(从0 开始)
# print(my_girl_friends[-1])  # 取出最后一个女友  反取(从-1开始)
# print(id(my_girl_friends))
# my_girl_friends[0]=‘fanbingbing‘
# print(id(my_girl_friends))    #  id没变

# 切片(顾头不顾尾,步长)
# print(my_girl_friends[0:2])     #取出前两个女友,默认步长1
# print(my_girl_friends[0:2:2])

# 长度
# print(len(my_girl_friends))

# 成员运算in和not in(判断列表的元素在不在列表里面)
# print(‘liutou‘in my_girl_friends)
# print(4 in my_girl_friends)
# print(6 not in my_girl_friends)

# 追加
# my_girl_friends.append([‘6号‘,‘7号‘])
# print(my_girl_friends)
# 删除
# del my_girl_friends[2] #通用的删,可以删除列表,字符串等
# print(my_girl_friends)
# print(my_girl_friends.remove(‘yangmi‘))  #remove:指定元素来删,单纯的删除,不会返回删除的值
# print(my_girl_friends)

# my_girl_friends.pop()       #pop按照索引来删,默认从末尾开始删 (-1)
# print(my_girl_friends)
# ghj=my_girl_friends.pop(1)          #取出删除的值,相当于剪切
# print(my_girl_friends)
# print(ghj)
# 循环


# 其他操作:
my_girl_friends=[‘yangmi‘,‘liuyifei‘,‘liutou‘,4,5,4] #本质my_girl_friends=list([...])
# my_girl_friends.insert(0,‘GHJ‘)  # 按照索引往前插值
# print(my_girl_friends)
# my_girl_friends.insert(2,‘FHM‘)
# print(my_girl_friends)

# my_girl_friends.extend([1,2,3,4,5])     #往列表最后加多个值
# print(my_girl_friends)

# print(my_girl_friends.count(4))         #统计指点元素的个数

# 了解:
# my_girl_friends.clear()   # 清空列表
# print(my_girl_friends)

# a=my_girl_friends.copy()      # 拷贝了一份列表
# print(a)

# my_girl_friends.reverse()     # 反转列表
# print(my_girl_friends)

# a=[3,5,1,9,-8]
# a.sort()        # 排序,从小到大排序
# print(a)
# a.sort(reverse=True)  # 从大到小排序
# print(a)

# 练习:
# 加值
# 对列:先进先出,扶梯
#append,pop
# a=[]
# a.append(‘first‘)
# a.append(‘second‘)
# a.append(‘third‘)
# print(a)
# print(a.pop(0))
# print(a.pop(0))
# print(a.pop(0))
# insert,pop
# 堆栈:先进后出,后进先出
a=[]
a.insert(0,‘first‘)
a.insert(0,‘second‘)
a.insert(0,‘third‘)
print(a)
print(a.pop(0))
print(a.pop(0))
print(a.pop(0))
# 删值
# remove   pop

 

元组类型

#!/usr/bin/env python
# Author:hongjie.gao
# 存任意多个值,有序,不可变
# 比列表占内存空间多   通常用在读的操作

# 定义方式:
A=(‘a‘,‘b‘,‘c‘,‘d‘)   #A=tuple(‘a‘,‘b‘,‘c‘,‘d‘)
# print(id(A),type(A),A)

#优先掌握的操作:
# 按索引取值(正向取+反向取):只能取
# print(A[2])     #正向取
# print(A[-2])   # 反向取
# 切片(顾头不顾尾,步长)
# print(A[0:2])       #产生了一个新的元组
# print(A)
# 长度
# print(len(A))
# 成员运算in和not in
# print(‘c‘in A)
# print(‘f‘ not  in A )

#其他操作:
# print(A.index(‘c‘))     #查看索引
# print(A.index(‘DADA‘))  #不存在就报错
#
# print(A.count(‘a‘))        #统计哥数
# #


# 字典的成员运算:


# msg_dic={
# ‘apple‘:10,
# ‘tesla‘:100000,
# ‘mac‘:3000,
# ‘lenovo‘:30000,
# ‘chicken‘:10,
# }
# # print(‘apple‘ in msg_dic)    # 对于字典来说成员运算判断的不是值,是key
#
# for key  in msg_dic:                     # for 循环不依赖索引,直接拿出值
#     print(key,msg_dic[key])                 # 每次打印出来都是无序 的

# for i in range(0,11,2):  #  按照索引来取值  range:指定起始位置,指定终止位置,顾头不顾尾,还可以指定步长  (和列表,元组很像)
# for i in range(10) # 不指定开始,代表从0到10,代表默认结束位置10
#     print(i)

#
# A=(‘a‘,‘b‘,‘c‘,‘d‘)
# for i in range(len(A)):
#     print(i,A[i])


# # 循环





#简单购物车,要求如下:
# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
#
# msg_dic={
# ‘apple‘:10,
# ‘tesla‘:100000,
# ‘mac‘:3000,
# ‘lenovo‘:30000,
# ‘chicken‘:10,
# }
# a=[]
# while True:
#     for key in msg_dic:
#         print(key, msg_dic[key])
#     choice = input(‘>>:‘).strip()
#     if choice not in msg_dic:
#         print(‘商品不存在‘)
#         continue
#     count = input(‘个数>>:‘).strip()
#     if not count.isdigit():
#         print(‘请输入数字‘)
#         continue
#     else:
#         a.append((choice, msg_dic[choice], int(count)))
#         print(a)


# while+else
# for i in range(5):
#     print(i)
# else:
#     print(‘ok‘)
#

# for i in range(5):
#     if i == 3:
#         break
#     print(i)
# else:
#     print(‘ok‘)

字典类型

#!/usr/bin/env python
# Author:hongjie.gao
#作用:存多个值,key-value存取,取值速度快
#定义:key必须是不可变类型,value可以是任意类型
# a={‘a‘:1}   #字符串可以当做字典的key
# b={1:2}     #数字可以做字典的key
# c={[‘a‘,2,‘mac‘]:3000}  #列表不可以做字典的key
# c={(‘a‘,2,‘mac‘):3000}      #元组可以做字典的key
# print(c[(‘a‘,2,‘mac‘)])


info={‘name‘:‘egon‘,‘age‘:18,‘sex‘:‘male‘} #本质info=dict({....})
# 或
# info=dict(name=‘egon‘,age=18,sex=‘male‘)
# 或
# info=dict([[‘name‘,‘egon‘],(‘age‘,18)])
# 或
# {}.fromkeys((‘name‘,‘age‘,‘sex‘),None)

#优先掌握的操作:
# 按key存取值:可存可取
# info={‘name‘:‘egon‘,‘age‘:18,‘sex‘:‘male‘}
# print(info[‘name‘])  #取   输入不存在的key报错
# info[‘hobbies‘]=[‘read‘,‘music‘,‘play‘,‘sleep‘]  #存
# print(info)
# 长度len
# print(len(info))
# 成员运算in和not in
#
#
# 删除
# print(info.pop(‘name‘))  #返回key对应的值
# print(info.pop(‘nameda a‘,None))    #没有key返回None
# 键keys(),值values(),键值对items()

# print(info.keys())  #打印所有key,dict_keys([‘name‘, ‘age‘, ‘sex‘]),不是列表类型,属于迭代类型
#
# for key in info.keys():
#     print(key)                  # 只取key,和默认的一样
#
# print(info.values())
# for val in  info.values():
#     print(val)                  # 只取值
#
# print(info.items())
for item in info.items():
    print(item[0],item[1])
# 循环

# 其他方法:
# info={‘name‘:‘egon‘,‘age‘:18,‘sex‘:‘male‘}
# info.fromkeys()
# print(info.get(‘dadaadadad‘))   #输入不存在的key不报错,打印None,也可以自己指定
# print(info.popitem())           #返回key和value

# info.setdefault()
# info.update()

# 补充两种赋值方式:
# 一:链式赋值
# x=10
# y=x
# x=y=z=10
# print(id(x),id(y),id(z))

# 交换两个变量的值
# m=10
# n=20
# m,n=n,m
# print(m,n)
# 二:从一个数据类型中解压出我们想要的值

# t=()

 

作业

#!/usr/bin/env python
# Author:hongjie.gao

menu = {
    ‘北京‘:{
        ‘海淀‘:{
            ‘五道口‘:{
                ‘soho‘:{},
                ‘网易‘:{},
                ‘google‘:{}
            },
            ‘中关村‘:{
                ‘爱奇艺‘:{},
                ‘汽车之家‘:{},
                ‘youku‘:{},
            },
            ‘上地‘:{
                ‘百度‘:{},
            },
        },
        ‘昌平‘:{
            ‘沙河‘:{
                ‘老男孩‘:{},
                ‘北航‘:{},
            },
            ‘天通苑‘:{},
            ‘回龙观‘:{},
        },
        ‘朝阳‘:{},
        ‘东城‘:{},
    },
    ‘上海‘:{
        ‘闵行‘:{
            "人民广场":{
                ‘炸鸡店‘:{}
            }
        },
        ‘闸北‘:{
            ‘火车战‘:{
                ‘携程‘:{}
            }
        },
        ‘浦东‘:{},
    },
    ‘山东‘:{},
}
print(‘输入q退出程序,输入B返回上一层‘)
q=True
while q:
    for i in menu:
        print( i)
    a=input(‘>:‘).strip()
    if a == ‘q‘:
        q = False
    elif a == ‘B‘:
        print(‘已经到顶层了‘)
    elif a in menu:
        while q:
            for o in menu[a]:
                print(o)
            b=input(‘>>:‘).strip()
            if b == ‘q‘:
                q = False
            elif b==‘B‘:
                break
            if b in menu[a]:
                while q:
                    for p in menu[a][b]:
                        print(p)
                    c = input(‘>>>:‘).strip()
                    if c == ‘q‘:
                        q = False
                    elif c == ‘B‘:
                        break
                    if c in menu[a][b]:
                        for r in menu[a][b][c]:
                            print(r)
                        z=input(‘>::‘)
                        if z == ‘q‘:
                            q=False
                        elif b == ‘B‘:
                            break
                        else:
                            print(‘我也是有底的‘)
                    else:
                        print(‘输入的地址不存在‘)
            else:
                 print(‘输入的地址不存在‘)
    else:
        print(‘输入的地址不存在‘)

 

#!/usr/bin/env python
# Author:hongjie.gao
# 简单购物车,要求如下:
# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
msg_dic = {
    ‘A‘: [‘手机‘, 1000],
    ‘B‘: [‘汽车‘, 100000],
    ‘C‘: [‘电脑‘, 3000],
    ‘D‘: [‘服务器‘, 30000],
    ‘E‘: [‘杯子‘,10]
}
# print(‘输入q退出程序‘)
a=[]
username=‘admin‘
password=‘123‘
count=0
ghj=True
while ghj:
    U=input(‘please input username>>:‘)
    if U==username:
        count = 0
        while ghj:
            P = input(‘please input password>>:‘)
            if P==password:
                print(‘Welcome to login‘)
                ghj=False
            else:
                count+=1
                if count==3:
                    print(‘wrong password‘)
                    ghj = False
    else:
        count+=1
        if count==3:
            print(‘wrong username‘)
            ghj = False
    print(‘输入q退出程序‘)
    while True:
        salary = input(‘请输入工资>>:‘)
        if  salary.isdigit():
            salary=int(salary)
        elif salary==‘q‘:
            exit()
        else:
            print(‘请输入数字‘)
            continue
        while True:
            for key in msg_dic:
                print(key, msg_dic[key])
            choice = input(‘>>:‘).strip()
            if choice==‘q‘:
                exit()
            elif choice not in msg_dic:
                print(‘商品不存在‘)
                continue
            else:
                a.append( msg_dic[choice])
                print(a)
                if  msg_dic[choice][1] <= salary:
                    salary -= msg_dic[choice][1]
                    print(salary)
                    continue
                else:
                    print(‘余额不足‘)

 

数据类型,字符串,文件处理

标签:变量   case   isl   等级   交换   ima   tuple   其他   for   

原文地址:http://www.cnblogs.com/huangtiandi001/p/7528412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!