小甲鱼教学笔记——元组、字符串

元组:带了枷锁的列表

  • 不可被修改
  • 逗号是关键,()不是关键

1.创建和访问元组

tuple1=(1,2,3,4,5,6,7,8,9)
tuple1
(1, 2, 3, 4, 5, 6, 7, 8, 9)
tuple1[1]
2
tuple1[5:]
(6, 7, 8, 9)
tuple2=tuple1
tuple2
(1, 2, 3, 4, 5, 6, 7, 8, 9)
tuple1[1]=3#不可以被修改
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-6-63750aca776b> in <module>
----> 1 tuple1[1]=3#不可以被修改


TypeError: 'tuple' object does not support item assignment
temp1=(1)
temp1
1
type(temp1)
int
temp2=1,2,3
temp2
(1, 2, 3)
type(temp2)
tuple
temp1=(1,)
type(temp1)
tuple
temp=[]#空列表
temp1=()#空元组
print(type(temp),type(temp1))
<class 'list'> <class 'tuple'>
8*(8)
64
8*(8,)
(8, 8, 8, 8, 8, 8, 8, 8)

2.更新和删除元组

temp=('吴亦凡','陈晓','胡歌','黄子韬')
temp=temp[:2]+('李沁','张予曦')+temp[2:]
temp
('吴亦凡', '陈晓', '李沁', '张予曦', '胡歌', '黄子韬')
del temp#删除元组,很少用,因为python有回收机制
temp
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-19-db4185758f4f> in <module>
      1 del temp
----> 2 temp


NameError: name 'temp' is not defined

3.可以用的相关操作符

  1. 拼接操作符:temp=temp[:2]+(‘李沁’,‘张予曦’)+temp[2:]
  2. 重复操作符:8*(8)
  3. 关系操作符:><=
  4. 逻辑操作符:or and is not …
  5. 成员操作符: in ,not in

字符串:

  • 各种奇怪的方法
str1='i love money'
str1[:6]
'i love'
str1[5]
'e'
str1=str1[:6]+'插入的字符串'+str1[6:]
str1
'i love插入的字符串 money'

1. capitalize():把首字母大写

str2='zheshixiaoxiezimu'
str2.capitalize()
'Zheshixiaoxiezimu'

2. casefold():全部改为小写

str2='ZHESHIxiaoxiezimu'
str2.casefold()
'zheshixiaoxiezimu'

3. center(width):居中

str2.center(50)
'                ZHESHIxiaoxiezimu                 '

4. S.count(sub[, start[, end]]) :查找子串出现的次数

str2.count('xi')
2

5.S.endswith(suffix[, start[, end]]) -> bool:判断是否以"suffix"结束

str2.endswith('mu')
True

6. S.find(sub[, start[, end]]) -> int:寻找子串

str3="i love china"
str3.find('hh')
-1
str3.find("china")
7

在这里插入图片描述

7. str4.istitle():首字母大写其余小写为标题

str4="Yuhongxia"
str4.istitle()
True

8. str4.join(iterable, /):以字符串为分隔符

str4.join("123456")
'1Yuhongxia2Yuhongxia3Yuhongxia4Yuhongxia5Yuhongxia6'

9. str5.lstrip(chars=None, /):去掉左边的空格

str5="    i love you"
str5.lstrip()
'i love you'

10. str5.partition(sep, /):分割

str5.partition("ov")
('    i l', 'ov', 'e you')

11. str5.replace(old, new, count=-1, /):替换

str5.replace("you","myself")
'    i love myself'

12. str5.split(sep=None, maxsplit=-1):吧字符串以“step”为界,切割为列表

str5.split()
['i', 'love', 'you']
str5.split('o')
['    i l', 've y', 'u']

13. str6.strip(chars=None, /):删掉指定字符串,默认空格

str6="          ssssssssssyyyyyyyyyyyyssssssuuu"
str6.strip()
'ssssssssssyyyyyyyyyyyyssssssuuu'
str6.strip("ssssss")
'          ssssssssssyyyyyyyyyyyyssssssuuu'

猜你喜欢

转载自blog.csdn.net/chairon/article/details/107922382