ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-04-06 15:02:22  阅读:170  来源: 互联网

标签:1.4 Linbo play python list1 数据类型 game print mystr


一、字符串

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)

四、下标和切片

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

  • 字符串实际上就是字符的数组,所以也支持下标索引

        name = 'Linbo'  :    

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

 

 

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

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

注意:选取的区间属于左闭右开型意型[   )。 即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。

           如果结束位为空,那么表明是到结尾.

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

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

  • 字符串

name = "Linbo"

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

标签:1.4,Linbo,play,python,list1,数据类型,game,print,mystr
来源: https://blog.csdn.net/alingbo/article/details/115440346

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有