Python3 菜鳥教程 筆記2 -- 數字和字符串

$ Python3 數字
@ Python 數字類型轉換
int(x) 將x轉換爲一個整數。
float(x) 將x轉換到一個浮點數。
complex(x) 將x轉換到一個複數,實數部分爲 x,虛數部分爲 0。
complex(x, y) 將 x 和 y 轉換到一個複數,實數部分爲 x,虛數部分爲 y。x 和 y 是數字表達式。

@ 除法
在整數除法中,除法 / 總是返回一個浮點數,如果只想得到整數的結果,丟棄可能的分數部分,可以使用運算符 //
注意:// 得到的並不一定是整數類型的數,它與分母分子的數據類型有關係。
[例]
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5.0//3
1.0
>>> 

@ Python 可以使用 ** 操作來進行冪運算
[例]
>>> 2**3
8
>>> 2**(-2)
0.25
>>> 

@ 在交互模式中,最後被輸出的表達式結果被賦值給變量 _ 
[例]
>>> a
(1+2j) 
>>> 1+_
(2+2j)
>>> 

 

$ Python3 字符串

https://www.runoob.com/python3/python3-string.html
@ Python字符串格式化
[例]
>>> print ("Today is %s and %s %d." % ('Friday', 'Oct', 18))
Today is Friday and Oct 18.
>>> 

@ Python三引號
python三引號允許一個字符串跨多行,字符串中可以包含換行符、製表符以及其他特殊字符。
典型用例:當你需要一塊HTML或者SQL時,這時用字符串組合,特殊字符串轉義將會非常的繁瑣。
所見即所得,WYSIWYG(What You See Is What You Get)

@ 在Python3中,所有的字符串都是Unicode字符串(16位)

@ Python 的字符串內建函數(如下的str爲一個字符串對象)

(1)str.capitalize()  -> 將字符串的第一個字符轉換爲大寫

(2)str.count(substr, start= 0,end=len(str)) -> 返回substr在str中出現的次數
sub -- 搜索的子字符串
start -- 字符串開始搜索的位置。默認爲第一個字符,第一個字符索引值爲0。
end -- 字符串中結束搜索的位置。字符中第一個字符的索引爲 0。默認爲字符串的最後一個位置。
[例]
>>> str1="I don't know what that that means in that sentence."
>>> len(str1)
51
>>> str1.count('that',18)
3
>>> str1[18:]
'that that means in that sentence.'
>>> 

(3)str.encode(encoding='UTF-8',errors='strict')
         bytes.decode(encoding="utf-8", errors="strict")   # encoding -- 要使用的編碼,如"UTF-8"
[例]
>>> str1 = "週五";
>>> str1_utf8 = str1.encode("UTF-8")
>>> str1_gbk = str1.encode("GBK")
>>> print("UTF-8 編碼:", str1_utf8,"UTF-8 解碼:", str1_utf8.decode('UTF-8','strict'))
UTF-8 編碼: b'\xe5\x91\xa8\xe4\xba\x94' UTF-8 解碼: 週五
>>> print("GBK 編碼:", str1_gbk,"GBK 解碼:", str1_gbk.decode('GBK','strict'))
GBK 編碼: b'\xd6\xdc\xce\xe5' GBK 解碼: 週五
>>> 

(4)str.startswith(substr, start=0,end=len(str))
         str.endswith(substr, start=0,end=len(str))
str -- 檢測的字符串。
substr -- 指定的子字符串。
start -- 可選參數用於設置字符串檢測的起始位置。
end -- 可選參數用於設置字符串檢測的結束位置。
[例]
>>> str1='Bee collect honey.'
>>> str1.startswith('Bee')
True
>>> str1.endswith('honey')
False
>>> str1.endswith('honey.')
True

(5)str.find(substr, start=0, end=len(str))
返回值:如果包含子字符串則返回開始的索引值,否則返回-1。
         str.rfind(substr, start=0, end=len(str))
類似於find()方法,不過是從右邊開始查找。
         str.index(substr, start=0, end=len(str))
跟find()方法一樣,不過如果str不在字符串中會報一個異常。
         str.rindex(substr, start=0, end=len(str))
類似於index()方法,不過是從右邊開始查找。
[例]
>>> str1="I don't know what that that means in that sentence."
>>> str1.find('that')
18
>>> str1.find('this')
-1
>>> str1.rfind('that')
37
>>> str1[37:]
'that sentence.'
>>> 
>>> str1.index('that')
18
>>> str1.index('this')
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    str1.index('this')
ValueError: substring not found
>>> 
>>> str1.rindex('that')
37
>>> 

(6)str.isalnum()    -> str的所有字符都是字母或數字則返回 True
         str.isalpha()     -> str的所有字符都是字母則返回 True
         str.isdigit()       -> str的所有字符都是數字則返回 True
         str.islower()     -> 如果字符串中包含至少一個字母,且字母都是小寫,則返回 True
         str.isupper()    -> 如果字符串中包含至少一個字母,且字母都是大寫,則返回 True
         str.istitle()        -> 如果字符串是標題化的(首字母大寫)則返回 True
         str.isdecimal()   -> 如果字符串只包含十進制字符,則返回 true
         str.isnumeric()   -> 如果字符串中只包含數字字符,則返回 True
                  數字可以是: Unicode 數字,全角數字(雙字節),羅馬數字,漢字數字。
         str.isspace()       ->  如果字符串中只包含空白,則返回 True
 [例]
>>> '    '.isspace()
True
>>> ''.isspace()
False
>>> '\t\r\n'.isspace()
True
>>> 

(7)str.expandtabs(tabsize=8) -> 把str中的tab符號轉爲空格,tab 符號默認的空格數是 8

(8)str.join(sequence)  -> 以指定字符串作爲分隔符,將 sequence 中所有的元素合併爲一個新的字符串
sequence -- 要連接的元素序列。可以是列表、元組或字符串,元素爲字符(否則會報錯)
[例]
>>> seq=[2019,10,18]     
>>> '-'.join(seq)
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    '-'.join(seq)
TypeError: sequence item 0: expected str instance, int found
>>> seq=['2019','10','18']
>>> '-'.join(seq)
'2019-10-18'
>>> 

(9)str.split(splitstr="", num=str.count(str))
str -- 分隔符,默認爲所有的空字符,包括空格、換行(\n)、製表符(\t)等。
num -- 分割次數。默認爲 -1, 即分隔所有。
[例]
>>> 'ab c\n\nde fg\rkl\r\n'.split()
['ab', 'c', 'de', 'fg', 'kl']
>>>
>>> str1='https://www.runoob.com/python3/python3-string-split.html'
>>> str1.split(':')
['https', '//www.runoob.com/python3/python3-string-split.html']
>>> str1.split('/')
['https:', '', 'www.runoob.com', 'python3', 'python3-string-split.html']
>>> str1.split('/',3)
['https:', '', 'www.runoob.com', 'python3/python3-string-split.html']
>>> str1.split('-',-1)
['https://www.runoob.com/python3/python3', 'string', 'split.html']
>>> 

(10)str.center(width[, fillchar])
           str.ljust(width[, fillchar])
           str.rjust(width[, fillchar])

width -- 字符串的總寬度。
fillchar -- 填充字符。

返回一個指定的寬度且居中/左對齊/右對齊的字符串,如果 width 小於字符串寬度直接返回字符串,否則使用 fillchar 去填充。
[例]
>>> str1='FileCollector Conf'
>>> print(str1.center(50,'*'))
****************FileCollector Conf****************
>>> 
>>> str2='Page 2'
>>> print(str2.rjust(50)+ '\n' + '-'*50)
                                            Page 2
--------------------------------------------------
>>> 

(11)str.lower()  -> 轉換字符串中所有大寫字符爲小寫
           str.upper()  -> 轉換字符串中所有小寫字符爲大寫
           str.swapcase()  -> 將字符串中大寫轉換爲小寫,小寫轉換爲大寫
           str.title()  -> 返回"標題化"的字符串,即首字母轉化爲大寫
[例]
>>> '8ddd'.title()
'8Ddd'
>>> '8ddd'.istitle()
False
>>> '8Ddd'.istitle()
True
>>> 
>>> 'Abcd'.swapcase()
'aBCD'
>>> 

(12)str.strip([chars])
           str.lstrip([chars]) 
           str.rstrip([chars])

用於移除字符串頭尾/左邊/右邊指定的字符(默認爲空格)或字符序列
[例]
>>> str1='<<<---Hahaha--->>>'
>>> str1.strip('-')
'<<<---Hahaha--->>>'
>>> str1.lstrip('<')
'---Hahaha--->>>'
>>> str1.rstrip('>')
'<<<---Hahaha---'
>>> str1[3:-3].strip('-')
'Hahaha'
>>> 

(13)str.replace(old, new[, max])
old -- 將被替換的子字符串。
new -- 新字符串,用於替換old子字符串。
max -- 可選字符串, 替換不超過 max 次。
[例]
>>> str1="I don't know what that that means in that sentence."
>>> str1.replace('that','this',2)
"I don't know what this this means in that sentence."
>>> 

(14)len(str) -> 返回字符串長度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章