零基础入门学习python-----读书笔记(二)

博客代码:180914

  • 元组:不可改变的列表

  • 元组的特征

>>> temp1 = (1)   #元组的特征是逗号(,);而不是小括号()
>>> temp2 = (1, 2, 3)
>>> temp3 = 1, 2, 3
>>> temp1  #依然为一个数
1
>>> temp2
(1, 2, 3)
>>> temp3
(1, 2, 3)
>>> (8,)    #只要有逗号,就表示元组
(8,)
  • 更新与删除元组

>>> temp = (1, 2, 3, 4)    #其他与列表方法基本相同
>>> temp = temp[:2] + (5,) + temp[2:]
>>> temp
(1, 2, 5, 3, 4)
  • 字符串

  • 字符串常用函数

  1. casefold()

>>> str = "CSDFcsd"    #将大写字母变成小写
>>> str.casefold()
'csdfcsd'

  2. count(sub[, start[, end]])

>>> str = "ASFDSDSDFREFRSD"    #查找字符串指定位置中字串的出现次数
>>> str.count('SD',0,len(str))    #len函数可求出字符串长度
3

  3. 查找字串位置

>>> str = "ASFDSDSDFREFRSD"    #使用find和index查找字串的位置,具体区别为找不到是的反应
>>> str.find("SDS")
4
>>> str.find("fsdf")    #find返回-1
-1
>>> str.index("SDS")
4
>>> str.index("fsdf")    #index抛出异常
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    str.index("fsdf")
ValueError: substring not found

  4. join()

>>> 'x'.join("Test")    #join的作用是将每一个分隔符插入到字符串
'Txexsxt'
>>> 'I' + ' ' + 'you'    #join较加号会减少内存复制以及垃圾回收,所以优先join
'I you'
>>> ' '.join(['I', 'you'])
'I you'

  5. replace()

>>> str = "I love you"    #指定字符交换
>>> str.replace("you", "she")
'I love she

  6. split()

>>> str = "I love you"    #与join作用相反,以分隔符为间隔拆分字符串
>>> str.split()
>>> str = "I love you"
>>> str.split(' ')
['I', 'love', 'you']

 

posted @ 2018-09-14 09:25  降腰  阅读(163)  评论(0编辑  收藏  举报