python 字串string 處理函式

2021-08-09 13:32:11 字數 1428 閱讀 2642

字串長度獲取:len(str)

例:print '%s length=%d' % (str,len(str))

字母處理

全部大寫:str.upper()

全部小寫:str.lower()

大小寫互換:str.swapcase()

首字母大寫,其餘小寫:str.capitalize()

首字母大寫:str.title()

格式化相關

獲取固定長度,右對齊,左邊不夠用空格補齊:str.ljust(width)

獲取固定長度,左對齊,右邊不夠用空格補齊:str.ljust(width)

獲取固定長度,中間對齊,兩邊不夠用空格補齊:str.ljust(width)

獲取固定長度,右對齊,左邊不足用0補齊

以上為最基本的處理,基本但可能不常用

字串搜尋相關

搜尋指定字串,沒有返回-1:str.find('t')

指定起始位置搜尋:str.find('t',start)

指定起始及結束位置搜尋:str.find('t',start,end)

從右邊開始查詢:str.rfind('t')

搜尋到多少個指定字串:str.count('t')

上面所有方法都可用index代替,不同的是使用index查詢不到會拋異常,而find返回-1

字串替換相關

替換old為new:str.replace('old','new')

替換指定次數的old為new:str.replace('old','new',maxreplacetimes)

print '%s replace t to *=%s' % (str,str.replace('t', '*'))

print '%s replace t to *=%s' % (str,str.replace('t', '*',1))

字串去空格及去指定字元

去兩邊空格:str.strip()

去左空格:str.lstrip()

去右空格:str.rstrip()

去兩邊字串:str.strip('d'),相應的也有lstrip,rstrip

(劃重點)此為字串處理最常用的幾類函式,需要熟練使用,掌握其用法。

字串判斷相關

是否以start開頭:str.startswith('start')

是否以end結尾:str.endswith('end')

是否全為字母或數字:str.isalnum()

是否全字母:str.isalpha()

是否全數字:str.isdigit()

是否全小寫:str.islower()

是否全大寫:str.isupper()

還用很多重要的處理函式沒有列出,spilt()也是乙個重要的字串處理函式,以後會持續更新

Python基礎 String字串

usr bin env python coding utf 8 1.單雙引號轉義及字串拼接 前台介面輸入 print hello print word print hello word print hello word print hel lo name input please input pri...

Python的字串操作string

python中的字串可以使用單引號,雙引號,三引號表示。單引號 與雙引號 代表的意思相同,但要注意配對著用。並不分成單引號代表乙個字元,雙引號代表乙個字串,實際上python中沒有char。三引號 or 相比於前兩者的的優勢是,三引號內部可以自由使用單引號與雙引號,可以用於描述一段對話中 因為裡面很...

快速學習 Python字串(String)

s abcd s abcd s abcdefg a s 0 訪問弟0個元素 l len s 字串的長度a hello b python 操作符 描述 例項 字串連線 a b 輸出結果 hellopython 重複輸出字串 a 2 輸出結果 hellohello 通過索引獲取字串中字元 a 1 輸出結...