python基礎(六) - 基本數據類型之序列類型


 

前言:python的基本數據類型可以分為三類:數值類型、序列類型、散列類型,本文主要介紹序列類型及其通用操作。

 

一、序列類型


1)字符串(str):用單引號('),雙引號("),三引號(三單引號'''或三雙引號""")來表示

2)列表(list):用[ ]中括號表示

3)元組(tuple):用()小括號表示

 

二、字符串str


 1.定義

 字符串定義:單引號、雙引號、三引號、str() 引號都是成對出現

 空字符串:s ='' (單引號對里沒有任何數據)

空字符:s =' ' (中間有一個空格)

a = 'test'
b = "book"
c = '''student'''
d = """tea"""
x = 123     # x是數值類型
y = str(x)    # 通過python內置函數str()轉換成字符串

2.字符串的常見操作

  • 字符串的拼接: +
  • 字符串的輸出:print(),輸出多個不同的數據用逗號隔開
  • 字符串轉義:\n換行 , r 防止轉義
  • 下標取值:[],默認下標從0開始,0,1,2.....,如果從后面倒序開始取,就是-1,-2,-3......
a = 'bo'
b = 'ok'
c = a + b   # 字符串拼接
print(c)

print('這是測試換行\n的字符串')
print(r'!@$#%#&"""這是防止轉義的字符串')
print(c[0])     # 下標取值 

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
book
這是測試換行
的字符串
!@$#%#&"""這是防止轉義的字符串
b


Process finished with exit code 0

3.字符串的常用方法

1)join字符串拼接

str1 = '000'
str2 = str1.join(('zhangsan','nan','18')
print(str2)
# 輸出結果
# zhangsan000nan00018
                 
str3 = ' '.join(str1)
print(str3)
# 輸出結果
# 0 0 0

2)find查找元素

  查找元素的位置,可以是單個元素,也可以查找字符串,如果找不到就返回-1

# find:查找元素,找到第一個返回對應的下標值,找不到返回-1
str1 = 'asdgsajl'
print(str1.find('a'))
print(str1.find('sa'))
print(str1.find('adadda'))

# 輸出結果
# 0
# 4
# -1

3)count統計元素個數

統計元素個數,可以是單個元素,也可以是字符串

str1 = 'asdgsajl'
print(str1.count('a'))

# 輸出結果
# 2

4)replace替換字符

可以替換單個元素,也可以替換字符串,從左到右會替換全部符合條件的,還可以指定替換次數

str1 = 'asdgsajl'
print(str1.replace('a','2'))
print(str1.replace('a','2',1))    # 只替換1次

# 輸出結果
# 2sdgs2jl
# 2sdgsajl

5)split字符串分割

split() 指定某個字符為分隔符,分割出來的結果放入一個列表

str1 = 'sdagsajl'
print(str1.split('a'))

# 輸出結果
# ['sd','gs','jl']

# 分割后取出第一個,按下標取值,下標從0開始
print(str1.split('a')[0])
# 輸出結果
# sd

6)upper、lower大小寫

  將英文字母全部轉成大寫、小寫

str1 = 'asdfgh'
print(str1.upper())

str2 = 'SDFGG'
print(str2.lower())

# 輸出結果
ASDFGH
sdfgg

7)strip去除空格換行符

去除首尾空格和換行符,另外還有lstrip()去除左邊的空格,rstrip()去除右邊的空格

str1 = ' asrfaada '
print(str1.strip())

# 輸出結果
# asrfaada

4.字符串格式化輸出

1)傳統格式化輸出%

  • 輸出整數 %d
  • 輸出浮點數 %f
  • 指定輸出小數點位數 %.2f (保留小數點后2位)
  • 輸出字符串 %s
  • 字符串截取 %.2s (保留兩個長度的字符串)
test = 'python'
num = 12345.45612
print('test是%s' % test)
print('test是%.2s' % test)
# print('test是%d' % test) # 因為test是一個字符串,使用%d會報錯
print('num是%d' % num)
print('num是%f' % num)
print('num是%.2f' % num)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
test是python
test是py
num是12345
num是12345.456120
num是12345.46

Process finished with exit code 0

2)format格式化輸出

用 { } 花括號作一個占位符,這種寫法比較流行

  • 不指定序號,自動取匹配 {}
  • 指定下標序號去匹配 [0] [1]
  • 保留兩位小數 {:.02f}
  • 百分比形式顯示 {:.2%}
print('{}{}{}'.format('test','','python'))  # 常用這種寫法
print('{}a{}a{}'.format('test','','python'))
print('{2}{0}{1}'.format('test','','python')) # 指定format下標

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
test是python
testa是apython
pythontest是

Process finished with exit code 0

 

三、元組tuple


 1.定義

通過()小括號來表示元組,元組中的數據可以是任意的,但元組是不可變類型的數據,元組定義之后無法修改其內部的元素

2.元組的常見操作

下標取值:元組內部的數據是有序的,可以通過下標取值

注意點:

t = () 是空元祖

t = (1,) 只有一個數據的時候,要在末尾加一個逗號

3.元組的方法

count:查找元素的個數,找不到會返回0

index:查找元素的下標,還可以指定查找范圍

t = ()  # 這是一個空元組
t2 = (1,)  # 只有一個元素
t3 = (1, 2, 3, 'sdfg', '張三' , 'sdfg')
res = t3.count('張三')
res2 = t3.count('sd')
res3 = t3.count('sdfg')
res4 = t3.index('sdfg')
res5 = t3.index('sdfg', 0, 4)
print(t, t2, t3, res, res2, res3,res4, res5)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
() (1,) (1, 2, 3, 'sdfg', '張三', 'sdfg') 1 0 2 3 3

Process finished with exit code 0

 

四、列表list


 1.定義

  • 列表用[] 中括號表示
  • 列表內部的元素可以是任意類型
  • 列表是使用最頻繁的數據類型之一

2.列表的常見操作

1)下標索引取值:列表內部的元素是有序的

2)修改元素的值:列表是可變類型數據,可以通過下標修改指定位置的值

li = [1, 2, 'ada', (1, 2)]  # 嵌套了一個元組,整個元組是一個元素
print(li[3])
li[3] = (1, 2, 3)
print(li)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
(1, 2)
[1, 2, 'ada', (1, 2, 3)]

Process finished with exit code 0

3.列表的方法

1)增:append、insert、extend

li = ['python', 'java', 'c', 'c++', 'go', 'ruby', 'html']

# 增加元素
# append:往列表的最后位置增加元素
li.append('php')
print(li)
li.append([11, 22, 33])  # 嵌套,加一個列表
print(li)

# insert:按指定位置插入,通過下標指定
li.insert(3, 'c#')
print(li)
li.insert(4, '[0,1]')  # 嵌套,指定位置加一個列表
print(li)

# extend:插入多個元素
li.extend(['aa', 'bb', 'cc'])
print(li)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
['python', 'java', 'c', 'c++', 'go', 'ruby', 'html', 'php']
['python', 'java', 'c', 'c++', 'go', 'ruby', 'html', 'php', [11, 22, 33]]
['python', 'java', 'c', 'c#', 'c++', 'go', 'ruby', 'html', 'php', [11, 22, 33]]
['python', 'java', 'c', 'c#', '[0,1]', 'c++', 'go', 'ruby', 'html', 'php', [11, 22, 33]]
['python', 'java', 'c', 'c#', '[0,1]', 'c++', 'go', 'ruby', 'html', 'php', [11, 22, 33], 'aa', 'bb', 'cc']

Process finished with exit code 0

2)刪:pop、remove、clear(還有一個關鍵字del刪除)

li = ['python', 'java', 'c', 'c++', 'go', 'ruby', 'html']

# 刪除元素
# remove:刪除指定元素,從前往后找,找到第一個刪除,只刪除第一個
li.remove('python')
print(li)

# pop:指定下標刪除,如果不傳下標,默認刪除最后一個,最后一個是-1
li.pop()
print(li)
li.pop(0)
print(li)

# clear:清空列表的所有元素
# li.clear()  這里不做運行

# del:關鍵字(關鍵字刪除) 把整個li列表從內存刪除了
# del li  這里不做運行
del li[1]    # 通過下標刪除某一個元素
print(li)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
['java', 'c', 'c++', 'go', 'ruby', 'html']
['java', 'c', 'c++', 'go', 'ruby']
['c', 'c++', 'go', 'ruby']
['c', 'go', 'ruby']

Process finished with exit code 0

3)查:index、count

li = ['python', 'java', 'c', 'c++', 'go', 'ruby', 'html']

# 查詢
# count:計數
print(li.count('python'))  # 統計元素的個數
# index:返回下標
print(li.index('java'))     # 查找元素的下標

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
1
1

Process finished with exit code 0

4)改:通過下標修改值

li = ['python', 'java', 'c', 'c++', 'go', 'ruby', 'html']

# 修改列表元素
li[1] = 'python'
print(li)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
['python', 'python', 'c', 'c++', 'go', 'ruby', 'html']

Process finished with exit code 0

5)其他:copy、reverse、sort

lii = [88,17,22,56,123,23,22,5]
# copy:對列表的元素倒序顯示
test = lii.copy()
print(test)

# sort:對數值排序,默認從小到大排序
lii.sort()      # 從小到大排序
print(lii)

lii.sort(reverse=True)   # 從大到小排序
print(lii)

# reverse:對列表的元素倒序顯示
lii.reverse()
print(lii)

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
[88, 17, 22, 56, 123, 23, 22, 5]
[5, 17, 22, 22, 23, 56, 88, 123]
[123, 88, 56, 23, 22, 22, 17, 5]
[5, 17, 22, 22, 23, 56, 88, 123]

Process finished with exit code 0

 

五、序列類型的通用操作


 1.下標取值

可以正向取,從0開始,也可以反向取,從-1開始

2.切片

[a:b] a代表起始位置,b終止位置,使用的是元素下標,左閉右開,需a<b ;

[a: b : ​c] c為步長,c為負時表示反切,從后面開始切,需a>b

# 內部元素按下標索引進行排序
# 切片[a:b]  左閉右開
#    [a:b:c]   為c步長

str1 = 'hello python !'
str2 = ['python','java','c++','c#','go','php']
str3 = (1,3,4)
print(str1[1])
print(str1[6:12])
print(str2[6:-2])

print(str1[::2])   # 毎2個元素為一步,取毎一步的第一個元素
print(str1[6:12:2])   # 取到python,步長為2,最后切片結果pto

# 步長為正:開始位置下標小於終止位置 a<b
# 步長為負:開始位置下標大於終止位置 a>b

print(str2[::-2])  # 從后面切起,2個元素為一步

print(str2[0:5:-2])   # 這樣是切不到元素的,思考一下為什么?
print(str2[5:0:-2])

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
e
python
[]
hlopto 
pto
['php', 'c#', 'java']
[]
['php', 'c#', 'java']

Process finished with exit code 0

3.獲取元素總數

len()

4.統計元素個數

count()

str1 = 'asdas'
li = [1,2]
# len():打印元素的個數
print(len(str1))
print(len(li))
# count():打印元素的個數
print(str1.count('a'))
print(li.count(1))

5.序列類型之間的轉換

  • str():可以將整個元組或列表強制轉換成一個字符串(基本不用)
  • list():將元組和字符串中的每個元素拿出來,組成一個列表
  • tuple():將列表和字符串中的每個元素拿出來,組成一個元組
# 序列類型之間的相互轉換
str1 = 'hello python !'
str2 = ['python','java','c++','c#','go','php']
str3 = (1,3,4)
print(str(str2))     # 將整個元組或列表強制轉換成一個字符串(基本不用)
print(str(str3))
print(list(str1))     # 將元組和字符串中的每個元素拿出來,組成一個列表
print(list(str3))
print(tuple(str1))    # 將列表和字符串中的每個元素拿出來,組成一個元組
print(tuple(str2))

運行結果:

C:\software\python\python.exe D:/myworkspace/test/test/test.py
['python', 'java', 'c++', 'c#', 'go', 'php']
(1, 3, 4)
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n', ' ', '!']
[1, 3, 4]
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n', ' ', '!')
('python', 'java', 'c++', 'c#', 'go', 'php')

Process finished with exit code 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM