python学习(第二天)——字符串、列表、元组、字典

字符串

1、下标和切片

1)下标:字符串相当于字符数组,可以使用下标索引

name = "hello"
# name[0] = 'h'

2)切片:

切片的语法:[起始:结束:步长](起始包含,结束不包含)

name = "hello"
print(name[0:3])
print(name[0:3:2])
print(name[-1]) # 取最后一个字母
print(name[3:]) # 取从第三个开始到最后一个字母
print(name[-1:-3:-1]) # 取从最后一个向前的两个字母
print(name[::-1]) # 取从最后一个到最前一个字母
print(name[-1::-1]) # 取从最后一个到最前一个字母



输出:
'hel'
'hlo'
'o'
'lo'
'ol'
'olleh'
'olleh'

2、字符串常见操作

1)find()函数

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

mystr.find(str, start=0, end= len(mystr)) 
mystr = "hello world!"
mystr.find("lo")
mystr.find("wor",0,5)
mystr.find("wor",0,10)

输出:
3
-1
6

2)index()函数

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

mystr.index(str, start=0, end=len(mystr))
mystr = "hello world!"
mystr.index("lo")
mystr.index("wor",0,5)
mystr.index("wor",0,10)

输出:
3
(会有异常报错)
6

3)rfind()函数

 从右往左找

4)rindex()函数

 从右往左找

5)count()函数

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

mystr.count(str, start=0, end=len(mystr))
>>>mystr = "hello world itcast and itcastcpp"
>>mystr.count("itcast")
2

6)replace()函数

把mystr中的str1替换成str2,如果count指定,则替换不超过count次(注意,替换后原值不变)

mystr.replace(str1, str2, mystr.count(str1))
>>>name="hello world ha ha"
>>>name. replace("ha","Ha")
'hello world Ha Ha'
>>>name. replace( "ha",Ha",1)
'hello world Ha ha'
>>>name="hello world ha ha"
'hello world ha ha'

7)split()函数

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

mystr.split(str=" " , 2)   #返回列表
>>>name="hello world ha ha"
>>>name.split(" ")
['hello','world','ha','ha']
>>>name.split(" ",2)
['hello','world','ha ha']

8)capitalize()函数

把字符串第一个字符大写

mystr.capitalize()   
>>>mystr = "hello world itcast and itcastcpp"
>>>mystr.capitalize()
'Hello world itcast and itcastcpp'

9)title()函数

把字符串每个首字母大写

mystr.title()   
>>>mystr = "hello world itcast and itcastcpp"
>>>mystr.title()
'Hello World Itcast And Itcastcpp'

10)lower()/upper()函数

把字符串所有大写字母小写/把字符串所有小写字母大写

mystr.lower()/mystr.upper()
>>>mystr = "HELLO world"
>>>mystr.lower()
'hello world'
>>>mystr.upper()
'HELLO WORLD'

11)startswith()/endswith()函数

检查字符串是否以xxx开头/检查字符串是否以xxx结尾,返回True或者False

mystr.startswith("obj")/mystr.endswith("txt")
>>>mystr = "hello world itcast and itcastcpp"
>>>mystr.startswith("hello")
True
>>>mystr.startswith("Hello")
False

12)ljust()/rjust()/center()函数

返回一个原字符串左/右/居中对齐,并使用空格填充至长度width的新字符串

mystr.ljust(width)/mystr.endswith(width)/mystr.center(width)
>>>mystr = "hello"
>>>mystr.ljust(10)
'hello     '
>>>mystr.rjust(10)
'     hello'
>>>mystr.center(9)
'  hello  '

13)lstrip()/rstrip()/strip()函数

删除mystr左边的空白字符/删除mystr右边的空白字符/删除mystr两边的空白字符

mystr.lstrip()/mystr.rstrip()
>>>mystr = "    hello    "
>>>mystr.lstrip()
'hello    '
>>>mystr.rstrip()
'    hello'
>>>mystr.strip()
'hello'

14)partition()/rpartition()函数

把mystr以str分割成三部分,str前,str和str后(有多个单词用rpartition()从右边开始切)

mystr.partition(str)
>>>mystr = "hello world itcast and itcastcpp"
>>>mystr.partition("itcast")
('hello world ','itcast',' and itcastcpp')
>>>mystr.rpartition("itcast")
('hello world itcast and ','itcast','cpp')

15)splitlines()函数

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

mystr.splitlines()
>>>mystr = "hello\nworld"
>>>print(mystr)
'hello'
'world'
>>>mystr.splitlines()
['hello','world']

16)isalpha()/isdigit()/isalnum()函数

如果mystr所有字符都是字母则返回True,否则返回False(isdigi()正好相反)
isalnum():如果mystr所有字符都是字母或数字则返回True,否则返回False

mystr.isalpha()/mystr.isdigit()/mystr.isalnum()
>>>mystr = "hello"
>>>mystr.isalpha()
True

17)isspace()函数

如果mystr中只包含空格,则返回True,否则返回False。

mystr.isspace()

18)join()函数

mystr(列表)中每个字符后面插入st,构造出一-个新的字符串

mystr.join(str)
>>>str = "_"
>>>li = ["my","name","is","hello"]
>>>li.join(str)
'my_name_is_hello'

列表

1、列表的概念

变量A的类型为列表
namesList = ["xiaoWang" , "xiaoZhang", "xiaoHua"]
比C语言的数组强大的地方在于列表中的元素可以是不同类型的
testList.[1,'a']
family = [] #空列表

demo1:
>>>namesList = ["xiaoWang" , "xiaoZhang", "xiaoHua"]
>>>print(nameList[0])
>>>print(nameList[1])
>>>print(nameList[2])
'xiaoWang'
'xiaoZhang'
'xiaoHua'

2、列表的循环遍历

1)for循环遍历
2)while循环遍历

demo2:获取文件后缀名并打印
nameList = ["01.py","02.doc","03.txt"]
#使用for循环
for tempName in nameList:
    index=tempName.rfind(".")
    print(tempName[index:])
print("---------分割线---------")
#使用while循环
i=0
while i<len(nameList):
    tempName=nameList[i]
    index=tempName.rfind(".")
    print(tempName[index:])
    i+=1
输出:
.py
.doc
.txt
---------分割线---------
.py
.doc
.txt

3、列表的增删改查

1)列表增加元素(append/extend/insert):

mystr.append(str)

追加单个元素到List的尾部,只接受一个参数,参数可以是任何数据类型,被追加的元素在List中保持着原结构类型

#demo3:
family = ["zhangsan","lisi","wangwu"]
print(family)
print("_"*30)

newName = input("请输入新名字:")
family.append(newName)
print(family)
输出:
['zhangsan', 'lisi', 'wangwu']
______________________________
请输入新名字:zhaosi
['zhangsan', 'lisi', 'wangwu', 'zhaosi']

#demo4:
list1=['H','E','L','L','O']
list2=['1','2','3','4']
list1.append(list2)
print(list1)
>>list1 = ['H', 'E', 'L', 'L', 'O', ['1', '2', '3', '4']]
#注意:
#list.append(object) 其实就是向列表中添加一个对象object
mystr.extend(str)

将一个列表中每个元素分别添加到另一个列表中,只接受一个参数

#demo5:
list1=['H','E','L','L','O']
list2=['1','2','3','4']
list1.extend(list2)
print(list1)
>>list1 = ['H', 'E', 'L', 'L', 'O', '1', '2', '3', '4']
mystr.insert(index,object)

将一个元素插入到列表中,第一个参数(index)是索引点,即插入的位置,第二个参数(object)是插入的元素

#demo6:
list1=['H','E','L','L','O']
object1 = "x"
list1.insert(1,object1)
print(list1)
>>list1 = ['H', 'x', 'E', 'L', 'L', 'O']

2)列表删除元素(del/pop/remove):

del()

删除任何位置处的列表元素, 若知道某元素在列表中的位置则可使用del语句,可以删除从一个位置到另一个位置之间的元素:del a[start,end]

>>> a = [3, 2, 4, 1]
>>> del a[1]
>>> a 
[3, 4, 1]
>>>del a[0,2]
[1]
pop()

可删除任意位置的元素并将其返回, 只需在括号内指定要删除元素的索引即可, 当括号内为空时则删除该列表最后一个元素并将其返回

>>> a = [3, 2, 1] 
>>> a.pop(1) 
2
>>> a 
[3, 1]
remove()

可根据值删除元素, 若不知所要删除元素在列表中的位置时可用remove()删除, 需要注意的是remove()所删除的元素是列表中第一个配对的值

>>> a = [3, 2, 1, 2] 
>>> a.remove(2) 
>>> a 
[3, 1, 2]

3)列表修改元素:

直接用列表下标查找后赋值即可

4)列表查找元素(in/not in/index/count):

in:如果存在那么结果为true,否则为false
not in:如果不存在那么结果为true,否则false
(一般用上面两种)
indexcount:与字符串查找用法相同

a = ['a', 'b', 'c', 'a', 'b']
>>>a.index('a', 1, 3) # 注意是左闭右开区间
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
>>> a.index('a', 1, 4)
3
>>> a.count('b')#返回找到的字符串的个数
2
>>> a.count('d')
0

4、列表的嵌套

一个列表中的元素又是列表,称为列表的嵌套

demo:
schoolNames = [['北京大学','清华大学'],['南开大学','天津大学'],['山东大学','中国海洋大学']]
for temp in schoolNames:
    print(temp)
print('_'*30)
for temp in schoolNames:
    for temp2 in temp:
        print(temp2)
    print('_'*30)
输出:
['北京大学', '清华大学']
['南开大学', '天津大学']
['山东大学', '中国海洋大学']
______________________________
北京大学
清华大学
______________________________
南开大学
天津大学
______________________________
山东大学
中国海洋大学
______________________________

元组

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

aTuple = ("et",99,88,7.7)

列表的功能除了修改其他都可以用于元祖

字典

1、字典的表示

用{}表示字典

info = {"name":"班长","id":100,"sex":"female","addr":"China"}

说明:
●字典和列表一样,也能够存储多个数据
●列表中找某个元素时,是根据下标进行的
●字典中找某个元素时,是根据’名字’(就是冒号:前面的那个值,例如上面代码中的’name’、 ‘id’、 ‘sex’)
●字典的每个元素由2部分组成,键:值.例如’name’班长’ ,'name’为键, '班长’为值
●字典中键相同,后面键的值会覆盖前面的同名键值

2、字典的访问:

demo1:
info = {"name":"班长","id":100,"sex":"female","addr":"China"}
print(info)
print(info["name"])
print(info["sex"])
print("-"*20)
print(info["age"])#访问没有的键会出错

输出:
{'name': '班长', 'id': 100, 'sex': 'female', 'addr': 'China'}
班长
female
--------------------
Traceback (most recent call last):
  File "test.py", line 43, in <module>
    print(info["age"])#访问没有的键会出错
KeyError: 'age'


demo2:
info = {"name":"班长","id":100,"sex":"female","addr":"China"}
print(info)
info["age"] = 90 #添加键值
print(info["age"])
print(info)
info["age"] = 20 #修改键值
print(info["age"])
print(info)

输出:
{'name': '班长', 'id': 100, 'sex': 'female', 'addr': 'China'}
90
{'name': '班长', 'id': 100, 'sex': 'female', 'addr': 'China', 'age': 90}
20
{'name': '班长', 'id': 100, 'sex': 'female', 'addr': 'China', 'age': 20}

3、字典的常见操作

1)len()

>>>info = {"name":"xiaowang","high":180}
>>>len(info)
2
>>>len(info["name"])
8

2)keys()/values()

>>> info = {"name":"xiaowang","high":180}
>>> info
{'name': 'xiaowang', 'high': 180}
>>> info.keys()
dict_keys(['name', 'high'])
>>> info.values()
dict_values(['xiaowang', 180])

3)items()

>>> info = {"name":"xiaowang","high":180}
>>> info.items()
dict_items([('name', 'xiaowang'), ('high', 180)])

4)has_key()/get()

dict.has_ key(key)如果key在字典中,返回True,否则返回False
(该方式在python3中已取消,使用get())

注意:根据键访问值,如果键不存在则会报错,因此在不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值

>>>info = {"name":"班长","id":100,"sex":"female","addr":"China"}
>>>age = info.get("age")
>>>age #'age'键不存在,所以age为None
>>>type(age)
<type 'NoneType'>
>>>age = info.get('age',18)#若info中不存在'age'这个键,就返回默认值
>>>age
18

5)emunerate()

打印下标(返回值是其下标)

>>> for x,y in enumerate(temp):
...     print(x,y)
...
0 ('name', 'xiaowang')
1 ('high', 180)

6)字典的遍历

>>>info = {"name":"xiaowang","high":180}
>>>temp =  info.items()
>>>temp
dict_items([('name', 'xiaowang'), ('high', 180)])
>>> for item in temp:
...     print(key,value)
('name', 'xiaowang')
('high', 180)
>>> for key,value in temp:
...     print(key,value)
name xiaowang
high 180
>>> for key,value in temp:
...     print(key)
...
name
high
>>> for key in info.keys():
...     print(key)
...
name
high
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值