1. 程式人生 > >[Python3] 011 字符串:給你們看看我的內置方法 第三彈

[Python3] 011 字符串:給你們看看我的內置方法 第三彈

its 文件的 所有 ive utf-8 示例 orm ror windows

目錄

  • 少廢話,上例子
    • 1. encode(encoding=‘utf-8‘, errors=‘strict‘)
    • 2. expandtabs([tabsize=8])
      • 借此機會簡單地說一說 print()
    • 3. format_map()
    • 4. replace(old, new[, count])
    • 5. split(step=None, maxsplit=-1)
    • 6. splitlines([keepends])
    • 7. startswith(prefix[, start[, end]])
    • 8. swapcase()
    • 9. title()
    • 10. zfill(width)

少廢話,上例子

1. encode(encoding=‘utf-8‘, errors=‘strict‘)

  • 釋義:
    1. 使用 encoding 指定的編碼格式對字符串進行編碼,默認為 utf-8,不區分大小寫
    2. errors 用於設置不同錯誤的處理方案,默認為 ‘strict‘,意為編碼錯誤引起一個UnicodeError
    3. errors 其他可能的值有:‘ignore‘, ‘replace‘, ‘xmlcharrefreplace‘, ‘backslashreplace‘ 以及通過 codecs.register_error() 註冊的任何值
    4. 直接看例子吧
  • 示例
# 例1

str1 = "YorkFish不是魚"
str_utf8 = str1.encode("UTF-8")
str_gbk = str1.encode("GBK")
 
print("編碼前: ", str1, end="\n\n")    # 設置 print 結尾為兩個回車,方便閱讀
 
print("UTF-8 編碼:", str_utf8)
print("GBK 編碼:", str_gbk, end="\n\n")
 
print("utf-8 默認解碼:", str_utf8.decode())     # 默認 encoding=‘utf-8‘,errors=‘strict‘
print("utf-8 解碼:", str_utf8.decode(‘utf-8‘,‘strict‘))   # utf-8 不區分大小寫
print("UTF-8 解碼:", str_utf8.decode(‘UTF-8‘,‘strict‘))
print("GBK 解碼:", str_gbk.decode(‘GBK‘,‘strict‘))        # gbk 也不區分大小寫
  • 運行結果

編碼前: YorkFish不是魚

UTF-8 編碼: b‘YorkFish\xe4\xb8\x8d\xe6\x98\xaf\xe9\xb1\xbc‘

GBK 編碼: b‘YorkFish\xb2\xbb\xca\xc7\xd3\xe3‘

utf-8 默認解碼: YorkFish不是魚

utf-8 解碼: YorkFish不是魚

UTF-8 解碼: YorkFish不是魚

GBK 解碼: YorkFish不是魚

  • 不直觀?來張截圖:
    技術分享圖片

2. expandtabs([tabsize=8])

  • 釋義:
    1. 將字符串中的 Tab 符號,即 \t,轉換為空格
    2. 如果不指定參數,默認空格數是 8
  • 示例
# 例2

str2 = "制表符攻擊:\t!!!"

print ("替換 \\t 符號前: " + str2)
print ("替換 \\t 符號後: " +  str2.expandtabs())
print ("用 16 個空格替換 \\t 符號: " +  str2.expandtabs(16))
  • 運行結果

替換 \t 符號前: 制表符攻擊: !!!

替換 \t 符號後: 制表符攻擊: !!!

用 16 個空格替換 \t 符號: 制表符攻擊: !!!

  • 不直觀?來張截圖:
    技術分享圖片

借此機會簡單地說一說 print()

  • 更完整的寫法:print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)
  • 默認情況下,將值打印到流或 sys.stdout
  • 可選關鍵字參數:
    1. file:類似於文件的對象(流);默認為當前的 sys.stdout
    2. sep:在值之間插入的字符串,默認為空格
    3. end:在最後一個值後追加的字符串,默認為換行符
    4. flush:whether to forcibly flush the stream 是否強制刷新數據流?
    5. fileflush 是要挖坑的節奏,待我學完來填平,編碼 Py011-1
  • 示例
# print()

name = "YorkFish"

print(name + name)
print(name, name)           # 註意輸出時有空格
print(name, name, sep=‘‘)   # sep 設置為不空格
print()                     # 輸出一次換行符
print(name, end=‘\n\n‘)     # windows 下輸出兩次換行符
print(name, end=‘ --- ‘)    # 意味著不換行
print(name)
  • 運行結果

YorkFishYorkFish

YorkFish YorkFish

YorkFishYorkFish

YorkFish --- YorkFish

  • 不直觀?來張截圖:
    技術分享圖片

3. format_map()

  • 釋義:使用映射中的替換返回 S 的格式化版本
  • 示例
# 例3 沒學到,只好從官方文檔中找了個例子

class Default(dict):
     def __missing__(self, key):
         return key

print(‘{name} was born in {country}‘.format_map(Default(name=‘Guido‘)))
  • 運行結果

Guido was born in country

  • 挖個坑,日後填平,編號 Py011-2

4. replace(old, new[, count])

  • 釋義:
    1. 將字符串中的 old 子字符串替換成 new 子字符串
    2. 如果 count 指定,則替換不超過 count
  • 示例
# 例4

str4 = "All things in their being are good for something."

print(str4.replace(‘i‘, ‘I‘))
print(str4.replace(‘i‘, ‘I‘, 3))
  • 運行結果

All thIngs In theIr beIng are good for somethIng.

All thIngs In theIr being are good for something.


5. split(step=None, maxsplit=-1)

  • 釋義:
    1. 返回字符串中的單詞列表,使用 sep 作為分隔符字符串
    2. 不帶參數默認以空格為分隔符切片字符串
    3. 如果 maxsplit 參數有設置,則僅分隔 maxsplit 個子字符串,返回切片後的子字符串拼接的列表
  • 示例
# 例5

name5_1 = "Y.o.r.k.F.i.s.h"
name5_2 = "Y.o.r.k.F.i.s.h.."

print(name5_1.split(‘.‘))
print(name5_1.split(‘.‘,maxsplit=4))
print(name5_2.split(‘.‘))       # . 前的空字符算一個;. 後也算一個
  • 運行結果

[‘Y‘, ‘o‘, ‘r‘, ‘k‘, ‘F‘, ‘i‘, ‘s‘, ‘h‘]

[‘Y‘, ‘o‘, ‘r‘, ‘k‘, ‘F.i.s.h‘]

[‘Y‘, ‘o‘, ‘r‘, ‘k‘, ‘F‘, ‘i‘, ‘s‘, ‘h‘, ‘‘, ‘‘]

  • 親兄弟:rsplit(sep=None, maxsplit=-1)
    • 類似於 split(step=None, maxsplit=-1),不過是從右邊開始分隔

6. splitlines([keepends])

  • 釋義:
    1. 按照 \n 分隔,返回一個包含各行作為元素的列表
    2. 如果 keepends 參數指定,則返回前 keepends
  • 示例
# 例6.1

str6 = "Cease to struggle \nand you cease to live.\n(Thomas Carlyle)"

print(str6.splitlines())        # 拆分後去掉換行符
print(str6.splitlines(True))    # 若 keepends 為 True,保留換行符
  • 運行結果

[‘Cease to struggle ‘, ‘and you cease to live.‘, ‘(Thomas Carlyle)‘]

[‘Cease to struggle \n‘, ‘and you cease to live.\n‘, ‘(Thomas Carlyle)‘]


  • splitlines() 與 split() 的區別
# 例6.2

print(‘‘.splitlines())
print(‘‘.split(‘\n‘))   # 註意兩者的區別

print("love at first sight.\n".splitlines())
print("love at first sight.\n".split(‘\n‘))
  • 運行結果

[]

[‘‘]

[‘love at first sight.‘]

[‘love at first sight.‘, ‘‘]


7. startswith(prefix[, start[, end]])

  • 釋義:
    1. 檢查字符串是否以指定前綴 prefix 開頭,prefix 只是代號,可以是任意字符串
    2. 如果是則返回 True,否則返回 False
    3. startend 與之前樣,可指定開頭或指定區域
  • 示例
# 例7

str7 = "The best is yet to come."

print (str7.startswith(‘The‘))
print (str7.startswith(‘is‘, 9))
print (str7.startswith(‘best‘, 4, 7))   # 和 endswith() 有些像,區域要大於指定字符長度
print (str7.startswith(‘best‘, 4, 8))
  • 運行結果

True

True

False

True

  • 表兄弟:endswith(sub[, start[, end]]) 見 第一彈

8. swapcase()

  • 釋義:翻轉字符串中的大小寫
  • 示例
# 例8

name8 = "YorkFish"
print(name8.swapcase())
  • 運行結果

yORKfISH


9. title()

  • 釋義:
    1. 返回“標題化”的字符串
    2. 標題化:所有的單詞都是以大寫開始,其余字母均小寫
  • 示例
# 例9

str9 = "the great gatsby"
print(str9.title())
  • 運行結果

The Great Gatsby


10. zfill(width)

  • 釋義:
    1. 返回長度為 width 的字符串
    2. 原字符串右對齊
    3. width 大於字符串長度,前邊用 0 填充
  • 示例
# 例10

name10 = "YorkFish"

print(name10.zfill(5))
print(name10.zfill(20))
print(name10.zfill())
  • 運行結果

YorkFish

000000000000YorkFish

TypeError……zfill() takes exactly one argument (0 given)

報錯是因為沒有輸入 width 參數。

別的也是:若方法的小括號中有參數,並且 1. 沒有用中括號括起來,2. 沒有默認值,都需要填上。


(元氣大傷!)

[Python3] 011 字符串:給你們看看我的內置方法 第三彈