金丹期前期:1.4、python语言-python的程序的核心数据类型:字符串、列表、元组、字典

 

一、字符串

1、字符串的表示方式

双引号或者单引号中的数据,就是字符串,如下所示:

   a = "hello itcast.cn"
   b = 'hello itcast.cn'

2、字符串的输出

name = "Linbo"                 #""双引号
position = '工程师'            #''单引号
address = "杭州市余杭区"

print('--------------------------------------------------')
print("姓名:%s"%name)
print("职位:%s"%position)
print("公司地址:%s"%address)
print('--------------------------------------------------')

3、字符串的输入

    userName = input('请输入用户名:')
    print("用户名为:%s"%userName)

    password = input('请输入密码:')
    print("密码为:%s"%password)

input获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存!!

4、字符串的常用操作(可认为是string对象的方法,但不改变原有字符串对象)

  • find:检测 str 是否包含在 mystr中,如果是返回str开始的索引值,否则返回-1

    #!/usr/bin/python3
    #coding=utf-8
    
    mystr = "Linbo, you have to play the game!!"
    str1  = "Linbo"
    str2  = "game"
    str3  = "them"
    
    l1= mystr.find(str1)
    l2= mystr.find(str2)
    l3= mystr.find(str3)
    
    
    print("Str1 local:%d"%l1)
    
    print("Str2 local:%d"%l2)
    
    print("Str3 local:%d"%l3)

    输出结果:

    Str1 local:0
    Str2 local:28
    Str3 local:-1
    

    关键词:初始位置为0,中间的字符和空格都是算位置的!!

  • index:跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo, you have to play the game!!"
str1  = "Linbo"
str2  = "game"
str3  = "them"

l1= mystr.find(str1)
print("Str1 local:%d"%l1)

l2= mystr.index(str2)
print("Str2 local:%d"%l2)

l3= mystr.index(str3)
print("Str3 local:%d"%l3)

输出结果:

Str1 local:0
Str2 local:28
Traceback (most recent call last):
  File "./1string.py", line 15, in <module>
    l3= mystr.index(str3)
ValueError: substring not found

关键词:index需要用在异常处理处使用!!

  • count:返回 str在start和end之间 在 mystr里面出现的次数

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo, you have to play the game!!"
str1  = "Linbo"
str2  = "game"
str3  = "a"

l1= mystr.find(str1)
print("Str1 local:%d"%l1)

l2= mystr.index(str2)
print("Str2 local:%d"%l2)

l3= mystr.count(str3)
print("Str3 count:%d"%l3)

执行结果:

Str1 local:0
Str2 local:28
Str3 count:3

 

  • replace(str1,str2,mystr.count(str)):把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo, you have to play the game!!"
str1  = "Linbo"
str2  = "game"
str3  = "a"
str4  = "life"

str5 = mystr.replace(str2,str4)
print("mystr:%s"%mystr)
print("ret_str:%s"%str5)


str7 = mystr.replace(str3,'c',2)
print("mystr:%s"%mystr)
print("ret_str:%s"%str7)

执行结果:

mystr:Linbo, you have to play the game!!
ret_str:Linbo, you have to play the life!!
mystr:Linbo, you have to play the game!!
ret_str:Linbo, you hcve to plcy the game!!

关键词:mystr字符串不会改变,运算结果是变换后的字符串

  • split:以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

list1 = mystr.split(" ")
print(list1)

list2 = mystr.split(" ",2)
print(list2)

执行结果:

['Linbo,', 'you', 'have', 'to', 'play', 'the', 'game!!']
['Linbo,', 'you', 'have to play the game!!']

关键词:分割之后的元素组成列表

  • capitalize:把字符串的第一个字符大写

  • title:把字符串的每个单词首字母大写

  • startswith:检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False

  • endswith:检查字符串是否以obj结束,如果是返回True,否则返回 False.

  • lower:转换 mystr 中所有大写字符为小写

  • upper:转换 mystr 中的小写字母为大写

print("%d"%mystr.startswith("Linbo"))
print("%d"%mystr.startswith("linbo"))
print("%d"%mystr.endswith("life!!"))
print("%d"%mystr.endswith("game!!"))
print("%s"%mystr.lower())
print("%s"%mystr.title())
print("%s"%mystr.lower())
print("%s"%mystr.upper())
print("%s"%mystr.lower())
print("%s"%mystr.capitalize())

执行结果:

1
0
0
1
linbo, you have to play the game!!
Linbo, You Have To Play The Game!!
linbo, you have to play the game!!
LINBO, YOU HAVE TO PLAY THE GAME!!
linbo, you have to play the game!!
Linbo, you have to play the game!!

 

  • ljust:返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

  • rjust:返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

  • center:返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

  • lstrip:删除 mystr 左边的空白字符

  • rstrip:删除 mystr 字符串末尾的空白字符

  • strip:删除mystr字符串两端的空白字符

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo, you have to play the game!!"
str1  = "       Linbo"
str2  = "game        "
str3  = "     a      "
str4 = "life"


print("=================================================")

print("%s"% mystr.ljust(50))
print("%s"% mystr.rjust(50))
print("%s"% mystr.center(50))

print("=================================================")
print(str1.lstrip())
print(str2.rstrip())
print(str3.strip())

执行结果:

=================================================
Linbo, you have to play the game!!                
                Linbo, you have to play the game!!
        Linbo, you have to play the game!!        
=================================================
Linbo
game
a

 

  • rfind:类似于 find()函数,不过是从右边开始查找

  • rindex:类似于 index(),不过是从右边开始.

  • partition:把mystr以str分割成三部分,str前,str和str后

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo, you have to play the game!!"
str1  = "       Linbo"
str2  = "game        "
str3  = "     a      "
str4 = "have to"


print(mystr.partition(str4))

执行结果:

('Linbo, you ', 'have to', ' play the game!!')

关键词:返回结果是一个元组.

  • rpartition:类似于 partition()函数,不过是从右边开始.

  • splitlines:按照行分隔,返回一个包含各行作为元素的列表

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo,\n you have to\n play the game!!"
str1  = "       Linbo"
str2  = "game        "
str3  = "     a      "
str4 = "have to"



print(mystr.splitlines())

执行结果如下:

['Linbo,', ' you have to', ' play the game!!']

关键词:执行结果为列表

  • isalpha:如果 mystr 所有字符都是字母 则返回 True,否则返回 False

  • isdigit:如果 mystr 只包含数字则返回 True 否则返回 False.

  • isalnum:如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

  • isspace:如果 mystr 中只包含空格,则返回 True,否则返回 False.

#!/usr/bin/python3
#coding=utf-8

mystr = "Linbo,you have to play the game!!"
str1  = "12344"
str2  = "game123445       "
str3  = "     a1  "
str4  = "     "

print(mystr.isalpha())
print(str1.isdigit())
print(str2.isalnum())
print(str3.isalpha())
print(str4.isspace())

执行结果如下:

False
True
False
False
True

 

  • join:list1中每个字符间隔处加一个"_",构造成一个新的字符串。

#!/usr/bin/python3
#coding=utf-8

list1 = ["Linbo","you","have to","play the game!!"]

print("-".join(list1))
print(" ".join(list1))

运行结果:

Linbo-you-have to-play the game!!
Linbo you have to play the game!!

二、列表

1、列表的格式及其打印方式

#!/usr/bin/python3
#coding=utf-8

list = [1,True,"Linbo",3.14]

print(list)
print(list[0])
print(list[1])
print(list[2])
print(list[3])

运行结果:

[1, True, 'Linbo', 3.14]
1
True
Linbo
3.14

关键词:列表内的元素可以是不同类型的,其数值打印方式可以整体打印也可以分开打印。

2、列表的遍历操作

为了更有效率的输出列表的每个数据,可以使用循环来完成

#!/usr/bin/python3
#coding=utf-8


list1 = [1,True,"Linbo",3.14]

print(list1)
print("===============")
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
print("===============")
for elem in list1:
        print(elem)
print("===============")
length = len(list1)

i = 0

while i<length:
        print(list1[i])
        i+=1

运行结果:

[1, True, 'Linbo', 3.14]
===============
1
True
Linbo
3.14
===============
1
True
Linbo
3.14
===============
1
True
Linbo
3.14

关键词:python中没有++操作符。while中要先定义变量,获取长度才能操作列表。

3、列表的常用操作(列表对象的方法,会改变列表对象本身)

添加元素

  • 末尾添加一个元素:list1.append(elem)
  • 末尾添加一组元素:   list1.extend(list2)
  • 指定位置添加元素:   list1.insert(index,elem)
#!/usr/bin/python3
#coding=utf-8


list1 = [1,True,"Linbo",3.14]
list2 = ["Linbo","have to","play game!!"]
print(list1)

print("=================")

list1.append(10)

print(list1)

print("=================")
list1.append(list2)
print(list1)
print("=================")

list1.extend(list2)
print(list1)
print("=================")

运行结果:

[1, True, 'Linbo', 3.14]
=================
[1, True, 'Linbo', 3.14, 10]
=================
[1, True, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!']]
=================
[1, True, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!'], 'Linbo', 'have to', 'play game!!']
=================
[1, True, 1111, 'Linbo', 3.14, 10, ['Linbo', 'have to', 'play game!!'], 'Linbo', 'have to', 'play game!!']

关键词:以下是错误的示例

list1 = ["Linbo","have to","play game!!"]

list1[3] = "11111"  #这种添加方式是错误的!!!
 

删除元素

  • del:根据下标进行删除
  • pop:删除最后一个元素
  • remove:根据元素的值进行删除
#!/usr/bin/python3
#coding=utf-8

list1 = ["Linbo","have to","play game!!"]

print(list1)
print("=================")
list1.pop()
print(list1)
print("=================")
list1.remove("Linbo")
print(list1)
print("=================")
del list1[0]
print(list1)
          

结果输出:

​
['Linbo', 'have to', 'play game!!']
=================
['Linbo', 'have to']
=================
['have to']
=================
[]

​

关键词:del不是方法,是个函数

修改元素

要通过下标来确定要修改的是哪个元素,然后才能进行修改

list1[0] = "play again"

查找元素

  • in(存在),如果存在那么结果为true,否则为false
  • not in(不存在),如果不存在那么结果为true,否则false
  • index与字符串中的用法一样
  • count与字符串中的用法一样
#!/usr/bin/python3
#coding=utf-8

list1 = ["Linbo","have to","play game!!"]

a= "Linbo"

if a in list1:
        print("list1 inlcude a")


print(list1.index(a,0,3))

print(list1.count("have to"))

运行结果:

list1 inlcude a
0
1

 

排序元素

  • sort:将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
  • reverse:是将list逆置.
#!/usr/bin/python3
#coding=utf-8

list1 = ["Linbo","have to","play game!!"]

print(list1)

list1.sort()
print(list1)

list1.sort(reverse=True)
print(list1)

list1.reverse()
print(list1)

 

运行结果:

['Linbo', 'have to', 'play game!!']
['Linbo', 'have to', 'play game!!']
['play game!!', 'have to', 'Linbo']
['Linbo', 'have to', 'play game!!']

4.列表可以嵌套使用

#encoding=utf-8

import random

# 定义一个列表用来保存3个办公室
offices = [[],[],[]]

# 定义一个列表用来存储8位老师的名字
names = ['A','B','C','D','E','F','G','H']

i = 0
for name in names:
    index = random.randint(0,2)    
    offices[index].append(name)

i = 1
for tempNames in offices:
    print('办公室%d的人数为:%d'%(i,len(tempNames)))
    i+=1
    for name in tempNames:
        print("%s"%name,end='')
    print("\n")
    print("-"*20)

三、元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号。

所以元组只能通过索引获取数据,不能修改数据,任何方式的修改元组的数值都会出错

元组的内置函数:

  • count:与字符串和列表中的用法相同
  • index:与字符串和列表中的用法相同

四、字典

1、字典的表示形式:{ }

info = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}
  • 字典和列表一样,也能够存储多个数据
  • 列表中找某个元素时,是根据下标进行的
  • 字典中找某个元素时,是根据'名字'(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')
  • 字典的每个元素由2部分组成,键:值。

2、根据key访问value

#! /usr/bin/python3
#encoding=utf-8

dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区',1:"hello"}

print(dict1)
print(dict1['name'])
print(dict1['id'])
print(dict1[1])
print(dict1['age'])

 运行结果:

{1: 'hello', 'id': 100, 'sex': 'M', 'address': '杭州市余杭区', 'name': 'Linbo'}
Linbo
100
hello
Traceback (most recent call last):
  File "./4dict.py", line 10, in <module>
    print(dict1['age'])
KeyError: 'age'

关键词:访问不存在的索引值会报错,key的数据类型可以是多样的

3、字典常用的操作

  • 获取元素:get(key)是另一种获取值的方法
  • 修改元素:只要通过key找到,即可修改
  • 添加元素:如果在使用 变量名['键'] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素

  • 删除元素:

    • del:del dict1['name'] 删除一个,del dict1 删除字典,删除不存在的也会报错
    • clear():清空整个字典
#! /usr/bin/python3
#encoding=utf-8

dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}

print(dict1)

print(dict1.get('name'))
print(dict1.get('age'))

dict1['id'] = 99
print(dict1)
dict1['age'] = 24
print(dict1)
del dict1['age']
print(dict1)
dict1.clear()
print(dict1)

 执行结果:

{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 100}
Linbo
None
{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 99}
{'address': '杭州市余杭区', 'name': 'Linbo', 'age': 24, 'sex': 'M', 'id': 99}
{'address': '杭州市余杭区', 'name': 'Linbo', 'sex': 'M', 'id': 99}
{}
  •  len:测量字典中,键值对的个数
  • keys:返回一个包含字典所有KEY的列表

  • values:返回一个包含字典所有value的列表

  • items:返回一个包含所有(键,值)元祖的列表

  • has_key:如果key在字典中,返回True,否则返回False

#! /usr/bin/python3
#encoding=utf-8

dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}

print(dict1)

print(len(dict1))
l1=dict1.keys()
print(l1)
print(dict1.values())
print(dict1.items())
print(dict1.has_key('name'))

运行结果:

{'name': 'Linbo', 'id': 100, 'sex': 'M', 'address': '杭州市余杭区'}
4
dict_keys(['name', 'id', 'sex', 'address'])
dict_values(['Linbo', 100, 'M', '杭州市余杭区'])
dict_items([('name', 'Linbo'), ('id', 100), ('sex', 'M'), ('address', '杭州市余杭区')])
Traceback (most recent call last):
  File "./4dict.py", line 13, in <module>
    print(dict1.has_key('name'))
AttributeError: 'dict' object has no attribute 'has_key'

 关键词:没有has_key???,

遍历字典的方法:

#! /usr/bin/python3
#encoding=utf-8

dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}

print(dict1)
print('=============')

for key in dict1.keys():
        print(key)
print('=============')
for value in dict1.values():
        print(value)
print('=============')
for item in dict1.items():
        print(item)

运行结果:

{'address': '杭州市余杭区', 'id': 100, 'name': 'Linbo', 'sex': 'M'}
=============
address
id
name
sex
=============
杭州市余杭区
100
Linbo
M
=============
('address', '杭州市余杭区')
('id', 100)
('name', 'Linbo')
('sex', 'M')

五、下标和切片(以字符串为例)

(1)列表与元组支持下标索引,字符串实际上就是字符的数组,所以也支持下标索引

        name = 'Linbo'  :    

name[0]name[1]name[2]name[3]name[4]name[5]
Linbo超出范围

 

(2)切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作

切片的语法:[起始:结束:步长]

注意:选取的区间属于左闭右开型意型[   )。 即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。           如果结束位为空,那么表明是到结尾.

           如果步长为负值,那么是往前数.

           如果结束为负值,-1表示是最后一个字符,但是记得左闭右开的原则

name = "Linbo"

切片                                      执行结果(右侧可以超出范围)

 

六、另一种通用的遍历方法(迭代器)

  • enumerate:遍历时候可以加上索引
#! /usr/bin/python3
#encoding=utf-8

dict1 = {'name':'Linbo', 'id':100, 'sex':'M', 'address':'杭州市余杭区'}

list1 = ['a', 'b', 'c', 'd']
for i, chr in enumerate(list1):
         print(i, chr)
print('======================')

t1 = (1,2,3,4)
for i, chr in enumerate(t1):
         print(i, chr)
print('======================')

for i, chr in enumerate(dict1):
         print(i, chr)

 运行结果:

0 a
1 b
2 c
3 d
======================
0 1
1 2
2 3
3 4
======================
0 id
1 address
2 sex
3 name

关键词:注意字典无顺序可言,而且只是key

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值