设为首页 加入收藏

TOP

day②-python基础(一)
2023-09-09 10:25:45 】 浏览:137
Tags:day -python 基础

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 文件操作
  6. 字符编码与转码 

1. 列表、元组操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表

names = ['Alex',"Tenglan",'Eric']

 通过下标访问列表中的元素,下标从0开始计数

 切片:取多个元素

>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
>>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
['Tenglan', 'Eric', 'Rain']
>>> names[1:-1] #取下标1至-1的值,不包括-1
['Tenglan', 'Eric', 'Rain', 'Tom']
>>> names[0:3]
['Alex', 'Tenglan', 'Eric']
>>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
['Alex', 'Tenglan', 'Eric']
>>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
['Rain', 'Tom', 'Amy']
>>> names[3:-1] #这样-1就不会被包含了
['Rain', 'Tom']
>>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
['Alex', 'Eric', 'Tom']
>>> names[::2] #和上句效果一样
['Alex', 'Eric', 'Tom']

 

追加

 

 

 

 

 

 copy真的这么简单么?那我还讲个屁。。。

 

 

 

 

2. 字符串操作   

特性:不可修改 

name.capitalize() 首字母大写
name.casefold() 大写全部变小写
name.center(50,"-") 输出 '---------------------Alex Li----------------------'
name.count('lex') 统计 lex出现次数
name.encode() 将字符串编码成bytes格式
name.endswith("Li") 判断字符串是否以 Li结尾
"Alex\tLi".expandtabs(10) 输出'Alex Li', 将\t转换成多长的空格
name.find('A') 查找A,找到返回其索引, 找不到返回-1

format :
>>> msg = "my name is {}, and age is {}"
>>> msg.format("alex",22)
'my name is alex, and age is 22'
>>> msg = "my name is {1}, and age is {0}"
>>> msg.format("alex",22)
'my name is 22, and age is alex'
>>> msg = "my name is {name}, and age is {age}"
>>> msg.format(age=22,name="ale")
'my name is ale, and age is 22'
format_map
>>> msg.format_map({'name':'alex','age':22})
'my name is alex, and age is 22'


msg.index('a') 返回a所在字符串的索引
'9aA'.isalnum() True

'9'.isdigit() 是否整数
name.isnumeric
name.isprintable
name.isspace
name.istitle
name.isupper
"|".join(['alex','jack','rain'])
'alex|jack|rain'


maketrans
>>> intab = "aeiou" #This is the string having actual characters.
>>> outtab = "12345" #This is the string having corresponding mapping character
>>> trantab = str.maketrans(intab, outtab)
>>>
>>> str = "this is string example....wow!!!"
>>> str.translate(trantab)
'th3s 3s str3ng 2x1mpl2....w4w!!!'

msg.partition('is') 输出 ('my name ', 'is', ' {name}, and age is {age}')

>>> "alex li, chinese name is lijie".replace("li","LI",1)
'alex LI, chinese name is lijie'

msg.swapcase 大小写互换


>>> msg.zfill(40)
'00000my name is {name}, and age is {age}'

 

>>> n4.ljust(40,"-")
'Hello 2orld-----------------------------'
>>> n4.rjust(40,"-")
'-----------------------------Hello 2orld'


>>> b="ddefdsdff_哈哈"
>>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
True

 

 

 

3. 字典操作

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

语法:

info = {
    'stu1101': "TengLan Wu",
    'stu1102': "LongZe Luola",
    'stu1103': "XiaoZe Maliya",
}

字典的特性:

  • dict是无序的
  • key必须是唯一的
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇第二章python基础语法1 下一篇Python 基础面试第三弹

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目