第五天
5.1 字符串對象
1、什麼是字符串
‘’、" " 、 " ““字符串””"、 ‘’‘字符串 ‘’’
2、字符串常見的方法
字符串可以被迭代,也可以通過下標訪問
注意:字符串是不可變類型
python中字符串的所有方法,並不會改動字符串本身的值!!!
而是返回值發生了變化
5.1.1 常用方法
|-- capitalize() # 首字母大寫
|-- center(width[,fillchar]) # 居中對象,第二個參數可選,表示要填充的符號,默認爲空格
|-- count(char) # 統計字符數量
|-- endswith(char) # 以xxx結束
|-- startswith(char) # 以x開始
|-- find(char) # 用來檢索某個字符或者字符串在該字符串中的第一次出現索引位置,如果找不到呢?則返回-1
|-- rfind(char) # 從最後一個向前查,但是下標並沒有發生變化
|-- index(char) # 用來檢索某個字符或者字符串在該字符串中的第一次出現索引位置,如果找不到呢?則拋出異常
|-- rindex(char) # 查找最後一個
|-- format() # 格式化字符串,python提出了,建議大家使用
|-- join(list) # 按照特定的規則拼接字符串
|-- split(char) # 按照特定的字符串分割字符串,結果是列表
|-- rsplit() # 從右
|-- upper() # 轉大寫
|-- lower() # 轉小寫
|-- strip() # 清除兩側的空格
|-- lstrip() # 清除左側空格
|-- rstrip() # 清除右側空格
|-- title() # 將字符串格式化爲符合標題的格式
|-- replace(old_str, new_str) # 替換字符串
|-- encode() # 將字符串轉換爲字節
注意:字節對象中有一個decode方法,可以將字節轉換爲對應編碼的字符串
is開頭的是用於判斷的
isalnum()
isalpha()
isdigit()
5.1.2 實際演示
capitalize()
>>> s = "hello,my name is eichi"
>>> s
'hello,my name is eichi'
>>> s.capitalize()
'Hello,my name is eichi'
center()
>>> s.center(50)
' hello,my name is eichi '
>>> s.center(50,"*")
'**************hello,my name is eichi**************'
count()
>>> s.count("l")
2
>>> s.count("i")
3
endswith()、startswith()
>>> s.endswith("xxx")
False
>>> s.endswith("i")
True
>>> s.endswith("eichi")
True
>>> s.startswith("hello")
True
>>> s.startswith("helo")
False
find()、index() 二者查詢時作用一致,區別在於find()找不到時,返回-1
>>> ss = "12345"
>>> ss.find("1")
0
>>> ss.find("5")
4
>>> ss.find("6")
-1
>>> ss.index("1")
0
>>> ss.index("3")
2
>>> ss
'12345'
>>> ss.index("1")
0
>>> ss.index("5")
4
>>> ss.index("6")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
rfind()、rindex()
>>> s = "hi,cool,hello"
>>> s.find("l")
6
>>> s.rfind("l")
11
>>> s.rfind("p")
-1
>>> s.rindex("p")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
format()
>>> num1 = 10
>>> num2 = 20
>>> print("{}+{}={}".format(num1,num2,num1+num2))
10+20=30
split()
>>> ss = "http://www.baidu.com"
>>> ss
'http://www.baidu.com'
>>> ss.split(".")
['http://www', 'baidu', 'com']
>>> ss.split("w")
['http://', '', '', '.baidu.com']
join()
>>> ls = ["1","2","3","4"]
>>> ls
['1', '2', '3', '4']
>>> " ".join(ls)
'1 2 3 4'
upper()、lower()
>>> ss = "hello,python"
>>> s = ss.upper()
>>> s
'HELLO,PYTHON'
>>> s.lower()
'hello,python'
encode()、decode()
>>> ss
'hello,python'
>>> ss.encode("utf-8")
b'hello,python'
>>> sb = ss.encode("utf-8")
>>> sb
b'hello,python'
>>> sb.decode("utf-8")
'hello,python'
5.2 切片
5.2.1 概述
切片是python提供給開發者用來分割、切割字符串或者其他有序可迭代對象的一種手段
字符串[index] # 訪問字符串的某個字符
字符串[start:] # 從start下標位置開始切割字符串,到末尾
字符串[start:end] # 從start下標位置開始切割字符串,切去end位置,不包含end 前閉後開區間[)
字符串[start:end:step] # step表示步長,默認是1,注意:如果step爲負數,表示從右向左切取
python是從在負索引的。最後一個位是-1,倒數第二個是-2,以此類推
注意:切片操作,如果下標不存在,並不會報錯,切片是用來切割字符串的,不會改變字符串的值
索引存在正負索引之分
正索引:從0到下標減一
負索引:從-1到-長度下標
字符串、元組、列表可以使用索引,集合不能使用索引(集合是無序的)
5.2.2 實際展示
>>> s = "0123456789"
>>> s[0]
'0'
>>> s[9]
'9'
>>> s[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[1:]
'123456789'
>>> s[1:8]
'1234567'
>>> s[4:]
'456789'
>>> s[1:7:2]
'135'
字符串中所有方法,並不能修改字符串本身的值
字符串是一個常量,python中沒有切割字符串的方法
面試題:
一行代碼反轉字符串
>>> s = "1234567"
>>> s[::-1]
'7654321'
>>> ls = list(s)
>>> ls
['1', '2', '3', '4', '5', '6', '7']
>>> ls.reverse()
>>> ls
['7', '6', '5', '4', '3', '2', '1']
5.3 函數
5.3.1 函數概述
1、什麼是函數
具有特殊功能的一段代碼的封裝
C語言是一門面向過程(功能、函數)的語言
具有名稱的一段具體功能代碼的統稱
2、爲什麼學習函數
代碼封裝、提高代碼的複用性、解耦合的作用
5.3.2 函數的定義
使用關鍵字 def # define function
def 函數名稱([參數列表]):
# 函數體
# [return 返回值]
調用函數的幫助文檔
print(print_msg.doc)
print(help(print_msg))
5.3.3 函數的調用
函數名稱([參數列數])
函數演示:
import math
def get_area(i,j,k):
p = 0.5 * (i+j+k)
s = math.sqrt((p*(p-i)*(p-j)*(p-k)))
return s
a,b,c = eval(input("請輸入三角形的三個邊的長度"))
x = get_area(a,b,c)
print('三邊爲{}、{}、{}的三角形的面積是:{:.2f}'.format(a,b,c,x))
#執行代碼
D:\網絡安全\Python\py_code>python Class3_三角形面積(函數).py
請輸入三角形的三個邊的長度3,4,5
三邊爲3、4、5的三角形的面積是:6.00
今天的內容到這裏就結束了~ 需要做題鞏固練習的,請保持關注,持續更新中ing