1. 程式人生 > >Python 基本資料型別(二): 字串型別

Python 基本資料型別(二): 字串型別

content

  • 字串的建立
  • 轉義序列
  • 字串的操作
  • 字串的相關方法

字串型別

1. 字串的建立
# 單引號、雙引號、三引號
# python2習慣使用單引號,python3之後習慣使用雙引號
#單引號、雙引號來定義字串作用幾乎一樣
a="hello"
b='hello'
print(a,b)
print(id(a),id(b))
# hello hello
# 2133525250488 2133525250488
# 單雙引號交替使用可以達到輸出對方的目的
# print("i am "ok"")
# invalid syntax

print
('i am "ok"') # 沒問題 i am "ok" print("i am 'ok''") # 注意:沒問題 i am 'ok''
a="ddd" \
  "dd"
print(a)
# ddddd
# 注意:\ 代表續行符,當字串定義的時候內容太多 ,需要換行,可以使用續行符連線

# 三引號,在定義的時候,直接包含換行
# 被使用當做多行註釋
a="鋤禾日當午,\n汗滴禾下土"
print(a)
# 鋤禾日當午,
# 汗滴禾下土
# 注意:\n 代表換行符
b="""
鋤禾日當午,
汗滴禾下土
"""
print(b)
# 鋤禾日當午,
# 汗滴禾下土
2. 轉義序列
# 當在定義字串的時候,希望輸出一些特殊的符號
# \ 轉義
print("i am \"ok\"")
# i am "ok"
# 如果不加\就會報錯
# \r 重啟一行(在linux使用)
print("aaaaa\rbbbb")
# bbbb
# \t製表符
print("aaaa\tbbbb")
# aaaa	bbbb
3. 字串的操作
(1)運算子
# 支援的運算子 +  *   in   not in    is   is not   ==   >   <
# + 兩個字串的拼接,新建立字串進行拼接
a="abc"
b="def"
print
(a+b) print(a,b) print("abc"+"def") # abcdef # abc def # abcdef
# * 字串的重複,新建立字串進行重複
a="abc"
b="def"
print(a*3)
print(a*2+b*3)
print(a,b)
a=a*3
print(a)
# abcabcabc
# abcabcdefdefdef
# abc def
# abcabcabc
# in not in 判斷元素是否在字串物件中
# in not in 判斷元素是否在字串物件中
a="abc"
b="def"
print("ac" in  a)
# is is not 判斷是否是同一個記憶體(是否是一個人?)
a="abc"
b="def"
print(a is b)
print(id(a),id(b))
# False
# 1644523122112 1644553432064
# 注意: 如果都是'abc',就是true
a = [1,2,3]
b = [1,2,3]
print(a is b)
print(id(a),id(b))
# False
# 2787243656136 2787243768648

# 總結:可變資料型別python不同id,不可變資料型別python 一樣的id(py聰明)
# ==判斷的是內容是否相等(長的是否一樣?)
# print(a ==b)

# 總結:is 和== : 如果is返回True,==一定返回True

#>  < 按照元素逐個比較,按照元素的ascii碼比較
print("abc"<"z")
# ord()
print(ord("a"))
print(ord("b"))
print(ord("c"))
print(ord("Z"))
# True
# 97
# 98
# 99
# 90

# len()函式 顯示object物件的長度
a="hello"
# print(len(a))

ascii碼圖:
在這裡插入圖片描述

(2)索引
# 訪問字串中單個元素
# 語法:字串名[index]
# index 是索引值,正數、負數、0
a="abcdefg"
# print(a[0])
# print(a[2])
# print(a[-1])
# print(a[100]) # string index out of range
b=""
print(len(b)) # 0
print(b[0]) # string index out of range

索引有界限,越界報錯
# a="hello"
#索引的界限  -len(object),len(object)-1   -6, 5
# 字串的元素不能修改
重要! 字串、數值、布林、位元組是不可變的資料型別
a="hello"
print(a[1])
a[1]="i"
print(a[1])
# 'str' object does not support item assignment
(3)切片
# 訪問字串中一定區域的多個元素
# 語法:字串名[start:end:step]
# start: 起始位置,正數(從左到右),負數(從右到左),預設值0
# end: 終止位置,預設值len(object)
# step:步長,預設1 ,正數(從左到右),負數(從右到左)
# 切片:從start位置開始,到end位置結束(不包含end),按照步長獲取字串中的元素
# start end  step都可以 正數、負數,但是要注意方向保持一致,否則無法擷取到資料
a="abcdefg"
print(a[0:len(a)])
print(a[0:7])
# abcdefg
# abcdefg

# a[2:5] 擷取元素的個數end-start
print(a[0:3])
print(a[0:3:2])

print(a[0:3:-2]) # 空,無結果,無報錯,因為start必須小於end

print(a[4:0:-2]) # ec,按照順序取,因為方向反了,start必須大於end
# print(a[:5])
# print(a[2:])
# print(a[2:7])
# print(a[-100:100]) # 切片的start和end是可以越界的,而索引不行
a="abcdefg"
# 整切片,字串、位元組的整切片是就原來物件的本身,不會重新建立。
# print(a[:])
# 逆序輸出
# print(a[::-1])
b=a[:]
print(a ==b) # True
print(a is b) # True
print(id(a),id(b),id(a[0:2])) # 第三個不是整切片
# 1879645995448 1879645995448 1879645995616
# 練習:
# 2018-10-10使用切片獲取年月日
d="2018-10-10"
print("年",d[:4])
print("月",d[5:7])
print("日",d[8:])
a="hello"
print(a,type(a))
# 字串物件中的方法帶有self,self代表當前物件自己,當呼叫方法的時候,不需要考慮self
4. 字串的相關方法
a="hello"
print(a,type(a))
# 字串物件中的方法帶有self,self代表當前物件自己,當呼叫方法的時候,不需要考慮self
(1)count()
# a.count(x,start,end)
# x是要統計的字串
# start:起始位置 ,0
# end:終止位置,len(str)
# 包含起始位置,不包含結束
a = 'hello'
print(a.count("l",1,5)) # 2
print(a.count("l",1,15)) # 2
print(a.count("0",0,1)) # 0
(2)index()
# 關於索引的方法找不到都會報錯。
# a.index(sub,start,end)
# sub:要查詢的子串
# start 、end:起始和終止
# 返回值:位置
a="hellohellohello"
# print(a.index("l"))
# print(a.index("l",5))
# # print(a.index("l",50))
(3)find()
# 同index,找不到不會報錯(脾氣好),返回-1
# 從左到右檢索查詢
# a="hellohellohello"
# print(a.find("p"))
# print(a.find("e"))
# # rfind和rindex都是從右向左查詢
# print(a.rfind("e"))

# 還可後面加索引的start和end
(4)join()
# 拼接 a.join(迭代物件):使用a將迭代物件中的每一個元素進行拼接
# print("-".join("abc"))

# 應用場合
li=["1","2","3"]
print("".join(li))
li=["1","2","3"]
print("".join(li))
# 123
(5)replace()
# a.replace(old,new,count)
# old 要替換的字串
#new 要替換成的字串
# count 替換的最大次數,預設全部替換
# a="hellohellohello"
print(a.replace("e","x",1))
print(a.replace("e","x",10))
# 注意:替換後的字串是新建立的。
(6)strip()
從兩端去掉、剪下,引數字串
# 會將兩端符合引數的字串去掉,直到遇到不符合的字串為止
a="hellohellohellohoh"
print(a.strip("h"))
# ellohellohelloho
print(a.strip("ho"))
# ellohellohell 會將兩端符合引數的字串去掉,直到遇到不符合的字串為止
print(a.strip("e"))
# hellohellohellohoh
print(a.strip("heo"))
# llohellohell
print(a.strip("hoe"))
# llohellohell 和上面結果一致,所以是不管順序的
# 左剪下和右剪下
print(a.lstrip("h"))
print(a.rstrip("h"))
(7)split()
# 切割,切割字元,被切割之後,就沒有了
# 重要:返回值是列表

# a="ab cd ef gh"
# print(a.split(" ")) ## ['ab', 'cd', 'ef', 'gh']

# b="abdcaabcabcddabddd" 
# print(b.split("a")) ## ['', 'bdc', '', 'bc', 'bcdd', 'bddd'] # 邊上的元素拆完了,前面就為空了
# b.split(sep,maxsplit) # maxsplit最大切割次數
b="abdcaabcabcddabddd"
print(b.split("a",2)) 
# ['', 'bdc', 'abcabcddabddd'] 只切了兩次a 第一次 第二次
print(b.split("a",20))
# ['', 'bdc', '', 'bc', 'bcdd', 'bddd']
# 注意:切割空白,不傳入引數,預設將所有空白都切除
# a="ab cd  ef   gh"
# print(a.split())
# ['ab', 'cd', 'ef', 'gh']
(8)splitlines()
# 按換行符切割
b="abdc\naa\nbca\nbcddabddd"
# 給多行切割
print(b.splitlines())
# ['abdc', 'aa', 'bca', 'bcddabddd']

b="abdc\naa\nbca\nbcddabddd"
# b.splitlines(keepends=) 是否保留換行符,預設不保留 = False,
print(b.splitlines(True))
# 保留換行符 ['abdc\n', 'aa\n', 'bca\n', 'bcddabddd']
(9)startswith()
# 判斷當前字串是否以指定字元開頭
# b="hello"
# print(b.startswith("h"))
# # print(b.startswith("ho"))
# start end:起始點、終止點
(10)endwith()
# 判斷當前字串是否以指定字元結束
# print(b.endswith("o"))
(11)upper() & lower()
# 將字串中的所有元素都轉換成大寫或者小寫
# a="heOlo"
# print(a.upper(),a)
# print(a.lower())
(12)isupper() & islower() & isspace()
# 判斷字串是否是大寫?小寫?空白?
# a="Hello"
# print(a.isupper())
# print(a.islower())
# b="\t"
# print(b.isspace())   #  空格 \r \t \n
(13)判斷字元和數值
# isalpha是否是字元(大寫小寫漢字)
print('a'.isalpha())
# True
# 是否是數字
print("123".isdigit())
# True
#判斷是否是數值
# 範圍:數值 > 數字 > 十進位制
# print("123".isnumeric())
# print("123".isdecimal())

(14)判斷字串是否是合法的識別符號
# 不能判斷關鍵字
print("1a1".isidentifier())
print("if".isidentifier())
# False
# True
(15)partition()
# 返回一個元組,第一個元素引數之前的,第二個元素是引數,第三個元素是引數之後
print("abcdefg".partition("de"))
# ('abc', 'de', 'fg')

(16)center()
# a.center(width,char)
# width:給定的長度
# char:填充的字串
# a="hell"
# print(a.center(6,"*")) #6 是給點的長度
#如果原來字串長度是奇數,填充的時候,從右側開始填充
a="hello"
print(a.center(6,"*"))
# hello*
#如果原來字串長度是偶數,填充的時候,從左側開始填充