Python3中操做字符串str必須記住的幾個方法

幾個Python的字符串經常使用內建函數html

1.方法:Python3 isdigit()方法python

 描述:Python isdigit() 方法檢測字符串是否只由數字組成。git

 語法:str.isdigit()函數

 參數:無學習

 返回值:若是字符串只包含數字則返回 True 不然返回 False。網站

 實例:this

 1 str = "123456"; 
 2 print (str.isdigit())
 3 
 4 str = "abcdef"
 5 print (str.isdigit())
 6 
 7 
 8 # 輸出結果
 9 True
10 False

 

2.方法:Python3 replace()方法url

 描述:replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),若是指定第三個參數max,則替換不超過 max 次。spa

 語法:str.replace(old, new[, max])翻譯

 參數:

  • old -- 將被替換的子字符串。
  • new -- 新字符串,用於替換old子字符串。
  • max -- 可選字符串, 替換不超過 max 次

 返回值:返回字符串中的 old(舊字符串) 替換成 new(新字符串)後生成的新字符串,若是指定第三個參數max,則替換不超過 max 次。

 實例:

 1 str = "www.w3cschool.cc"
 2 print ("菜鳥教程舊地址:", str)
 3 print ("菜鳥教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
 4 
 5 str = "this is string example....wow!!!"
 6 print (str.replace("is", "was", 3))
 7 
 8 
 9 # 輸出結果
10 菜鳥教程舊地址: www.w3cschool.cc
11 菜鳥教程新地址: www.runoob.com
12 thwas was string example....wow!!!

 

3.方法:Python3 find()方法

 描述:find() 方法檢測字符串中是否包含子字符串 str ,若是指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,若是指定範圍內若是包含指定索引值,返回的是索引值在字符串中的起始位置。若是不包含索引值,返回-1。

 語法:str.find(str, beg=0, end=len(string))

 參數:

  • str -- 指定檢索的字符串
  • beg -- 開始索引,默認爲0。
  • end -- 結束索引,默認爲字符串的長度。

 返回值:若是包含子字符串返回開始的索引值,不然返回-1。

 實例:

 1 str1 = "Runoob example....wow!!!"
 2 str2 = "exam";
 3  
 4 print (str1.find(str2))
 5 print (str1.find(str2, 5))
 6 print (str1.find(str2, 10))
 7 
 8 # 輸出結果
 9 7
10 7
11 -1

 擴展實例(Python 3.0+):

 1 # 實例(Python 3.0+)
 2 
 3 >>>info = 'abca'
 4 >>> print(info.find('a'))      # 從下標0開始,查找在字符串裏第一個出現的子串,返回結果:0
 5 0
 6 >>> print(info.find('a', 1))   # 從下標1開始,查找在字符串裏第一個出現的子串:返回結果3
 7 3
 8 >>> print(info.find('3'))      # 查找不到返回-1
 9 -1
10 >>>

 

4.方法:Python3 count()方法

 描述:count() 方法用於統計字符串裏某個字符出現的次數。可選參數爲在字符串搜索的開始與結束位置。

 語法:str.count(sub, start= 0,end=len(string))

 參數:

  • sub -- 搜索的子字符串
  • start -- 字符串開始搜索的位置。默認爲第一個字符,第一個字符索引值爲0。
  • end -- 字符串中結束搜索的位置。字符中第一個字符的索引爲 0。默認爲字符串的最後一個位置。

 返回值:該方法返回子字符串在字符串中出現的次數。

 實例:

 1 str="www.runoob.com"
 2 sub='o'
 3 print ("str.count('o') : ", str.count(sub))
 4 
 5 sub='run'
 6 print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
 7 
 8 
 9 # 輸出結果
10 str.count('o') :  3
11 str.count('run', 0, 10) :  1

 

5.方法:Python3 strip()方法

 描述:Python strip() 方法用於移除字符串頭尾指定的字符(默認爲空格)。

 語法:str.strip([chars]);

 參數:

  • chars -- 移除字符串頭尾指定的字符。

 返回值:返回移除字符串頭尾指定的字符生成的新字符串。

 實例:

1 str = "*****this is string example....wow!!!*****"
2 print (str.strip( '*' ))
3 
4 
5 # 輸出結果
6 this is string example....wow!!!

 

6.方法:Python3 split()方法

 描述:split()經過指定分隔符對字符串進行切片,若是參數num 有指定值,則僅分隔 num 個子字符串

 語法:str.split(str="", num=string.count(str))

 參數:

  • str -- 分隔符,默認爲全部的空字符,包括空格、換行(\n)、製表符(\t)等。
  • num -- 分割次數。

 返回值:返回分割後的字符串列表。

 實例:

 1 str = "this is string example....wow!!!"
 2 print (str.split( ))
 3 print (str.split('i',1))
 4 print (str.split('w'))
 5 
 6 
 7 # 輸出結果
 8 ['this', 'is', 'string', 'example....wow!!!']
 9 ['th', 's is string example....wow!!!']
10 ['this is string example....', 'o', '!!!']

 

7.方法:Python3 center()方法

 描述:center() 方法返回一個指定的寬度 width 居中的字符串,fillchar 爲填充的字符,默認爲空格。

 語法:str.center(width[, fillchar])

 參數:

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

 返回值:返回一個指定的寬度 width 居中的字符串,若是 width 小於字符串寬度直接返回字符串,不然使用 fillchar 去填充。

 實例:

1 str = "[www.runoob.com]"
2 
3 print ("str.center(40, '*') : ", str.center(40, '*'))
4 
5 
6 # 輸出結果
7 str.center(40, '*') :  ************[www.runoob.com]************

 

8.方法:Python3 join()方法

 描述:Python join() 方法用於將序列中的元素以指定的字符鏈接生成一個新的字符串。

 語法:str.join(sequence)

 參數:

  • sequence -- 要鏈接的元素序列。

 返回值:返回經過指定字符鏈接序列中元素後生成的新字符串。

 實例:

 1 s1 = "-"
 2 s2 = ""
 3 seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
 4 print (s1.join( seq ))
 5 print (s2.join( seq ))
 6 
 7 
 8 # 輸出結果
 9 r-u-n-o-o-b
10 runoob

 

9.方法:Python3 maketrans()方法

 描述:

 

  1. maketrans() 方法用於建立字符映射的轉換表,對於接受兩個參數的最簡單的調用方式,第一個參數是字符串,表示須要轉換的字符,第二個參數也是字符串表示轉換的目標。
  2. 兩個字符串的長度必須相同,爲一一對應的關係。

   注:Python3.4已經沒有string.maketrans()了,取而代之的是內建函數: bytearray.maketrans()、bytes.maketrans()、str.maketrans()

 

 語法:str.maketrans(intab, outtab)

 參數:

  • intab -- 字符串中要替代的字符組成的字符串。
  • outtab -- 相應的映射字符的字符串。

 返回值:返回字符串轉換後生成的新字符串。

 實例:

 1 intab = "aeiou"
 2 outtab = "12345"
 3 trantab = str.maketrans(intab, outtab)
 4 
 5 str = "this is string example....wow!!!"
 6 print (str.translate(trantab))
 7 
 8 
 9 # 輸出結果
10 th3s 3s str3ng 2x1mpl2....w4w!!!

 

10.方法:Python3 translate()方法

  描述:translate() 方法根據參數table給出的表(包含 256 個字符)轉換字符串的字符,要過濾掉的字符放到 deletechars參數中。

  語法:

  • str.translate(table[, deletechars]);
  • bytes.translate(table[, delete])
  • bytearray.translate(table[, delete])

  參數:

  • table -- 翻譯表,翻譯表是經過 maketrans() 方法轉換而來。
  • deletechars -- 字符串中要過濾的字符列表。

  返回值:返回翻譯後的字符串,若給出了 delete 參數,則將原來的bytes中的屬於delete的字符刪除,剩下的字符要按照table中給出的映射來進行映射 。

  實例:

實例(Python 3.0+)
 1 intab = "aeiou"
 2 outtab = "12345"
 3 trantab = str.maketrans(intab, outtab)   # 製做翻譯表
 4  
 5 str = "this is string example....wow!!!"
 6 print (str.translate(trantab))
 7 
 8 
 9 # 輸出結果
10 th3s 3s str3ng 2x1mpl2....w4w!!!

  實例:演示過濾掉字符'o'

1 # 製做翻譯表
2 bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
3  
4 # 轉換爲大寫,並刪除字母o
5 print(b'runoob'.translate(bytes_tabtrans, b'o'))
6 
7 
8 # 輸出結果
9 b'RUNB'

 

11.方法:Python format 格式化函數

  描述:

  1. Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它加強了字符串格式化的功能。
  2. 基本語法是經過 {} 和 : 來代替之前的 % 。
  3. format 函數能夠接受不限個參數,位置能夠不按順序。

  

實例
 1 >>>"{} {}".format("hello", "world")    # 不設置指定位置,按默認順序
 2 'hello world'
 3  
 4 >>> "{0} {1}".format("hello", "world")  # 設置指定位置
 5 'hello world'
 6  
 7 >>> "{1} {0} {1}".format("hello", "world")  # 設置指定位置
 8 'world hello world'
 9 
10 >>> 

  也能夠設置參數:

實例
 1 # -*- coding: UTF-8 -*-
 2  
 3 print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
 4  
 5 # 經過字典設置參數
 6 site = {"name": "菜鳥教程", "url": "www.runoob.com"}
 7 print("網站名:{name}, 地址 {url}".format(**site))
 8  
 9 # 經過列表索引設置參數
10 my_list = ['菜鳥教程', 'www.runoob.com']
11 print("網站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必須的
12 
13 
14 # 輸出結果
15 網站名:菜鳥教程, 地址 www.runoob.com
16 網站名:菜鳥教程, 地址 www.runoob.com
17 網站名:菜鳥教程, 地址 www.runoob.com

  也能夠向str.format() 傳入對象

實例
 1 # -*- coding: UTF-8 -*-
 2  
 3 class AssignValue(object):
 4     def __init__(self, value):
 5         self.value = value
 6 my_value = AssignValue(6)
 7 print('value 爲: {0.value}'.format(my_value))  # "0" 是可選的
 8 
 9 
10 # 輸出結果
11 value 爲: 6

  數字格式化

  下表展現了 str.format() 格式化數字的多種方法:

1 >>> print("{:.2f}".format(3.1415926));
2 3.14
數字 格式 輸出 描述
3.1415926 {:.2f} 3.14 保留小數點後兩位
3.1415926 {:+.2f} +3.14 帶符號保留小數點後兩位
-1 {:+.2f} -1.00 帶符號保留小數點後兩位
2.71828 {:.0f} 3 不帶小數
5 {:0>2d} 05 數字補零 (填充左邊, 寬度爲2)
5 {:x<4d} 5xxx 數字補x (填充右邊, 寬度爲4)
10 {:x<4d} 10xx 數字補x (填充右邊, 寬度爲4)
1000000 {:,} 1,000,000 以逗號分隔的數字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指數記法
13 {:10d}         13 右對齊 (默認, 寬度爲10)
13 {:<10d} 13 左對齊 (寬度爲10)
13 {:^10d}     13 中間對齊 (寬度爲10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
進制
  1. ^, <, > 分別是居中、左對齊、右對齊,後面帶寬度, : 號後面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。
  2. + 表示在正數前顯示 +,負數前顯示 -;  (空格)表示在正數前加空格
  3. b、d、o、x 分別是二進制、十進制、八進制、十六進制。

  此外咱們能夠使用大括號 {} 來轉義大括號,以下實例:

實例
1 # -*- coding: UTF-8 -*-
2  
3 print ("{} 對應的位置是 {{0}}".format("runoob"))
4 
5 
6 # 輸出結果
7 runoob 對應的位置是 {0}

 

  以上內容摘至菜鳥教程,爲學習Python中字符串經常使用內建函數的學習筆記,僅供參考,如存在錯誤請指出,萬分感謝!

  以上僅爲Python中字符串部分經常使用內建函數,更多字符串內建函數請參閱菜鳥教程-http://www.runoob.com/python3/python3-string.html

相關文章
相關標籤/搜索