1. 程式人生 > >python-字符串操作分類小結

python-字符串操作分類小結

編碼 方法 進行 start join lower isa space lse

切片

    str[start:end:step] # 包括頭,不包括尾巴。step為步長,意思是每隔step-1個元素,取一個字符
    
    [::-1] #反向取字符串,實現字符串的反轉 "abcde"-->"edcba"。

方法

字符串的修飾

center: 讓字符串在指定的長度居中,如果不能居中,左短右長
    "while".center(10) # while    
    "while".center(10, 'a') # aawhileaaa   可以指定填充內容,默認以空格填充
    len("while".center(10)) # 10
ljust:左對齊
    "while".ljust(10,'*') # while*****
rjust:右對齊
    "while".rjust(10,'*') # *****while
zfill:將字符串填充到指定的長度,不足的地方用0從左開始補充
    "1".zfill(10) --》 0000000001'
format: 按照順序將後面的參數傳遞給前面的大括號
    "{} is {} years old".format("while", 18) --> while is 18 years old
strip:默認去除字符串兩邊的空格,去除內容可以指定
rstrip:默認去除字符串左邊的空格,去除內容可以指定
lstrip:默認去除字符串右邊的空格,去除內容可以指定
join
    "a".join("123") # 1a2a3
len 方法返回指定序列的長度

字符串的查找

count:計數功能,返回指定字符在字符串中的個數
    "hello".count('l') # 2
find:查找,返回從左往右第一個指定字符的索引,如果找不到則返回-1
    "hello".find('l') # 2
strs1[index] = strs1[index - len(strs1)]
rfind: 查找,返回從右往左第一個指定字符的索引
index: 和find效果一樣,區別在於,找不到則報錯
rindex: 和rfind效果一樣,區別在於,找不到則報錯

字符串的替換

replace:從左到右替換指定的元素,可以指定替換的個數,默認全部替換
    "helllo".replace("l", "L") 將所有的l替換為L
    "helllo".replace("l", "L", 2) 將l替換為L,只替換2個
translate: 按照對應關系來替換內容
    trans = str.maketrans("12345", "abcde")
    "12123123".translate(trans) # ababcabc

字符串的變形

upper:將字符串當中所有的字符轉化為大寫
    "While".upper() --》 WHILE
lower:將字符串當中所有的字符轉化為小寫
    "While".upper() --》 while
swapcase: 將字符串當中所有的字符大小寫進行反轉
    "While".swapcase() --》 wHILE
title: 將字符串當中的單詞首字母大寫,單詞以空格劃分
    "While is ok ".title() --》 While Is Ok
capitalize: 只有字符串的首字符大寫
    "while IS ok ".capitalize() --》 While is ok
expandtabs: 修改\t的長度,很少用
    "while is ok 1993 ab c de".expandtabs() 無效果
    "while is \t ok 1993 ab c de".expandtabs(4) --> while is     ok 1993 ab c de

字符串的判斷

isalnum: 字符串是否只包含字母[a-zA-Z]和數字[0-9]
isalpha:字符串是否只包含字母[a-zA-Z]
isdigit: 字符串是否只包含數字[0-9]
isupper: 字符串是否只包含大寫字母
islower: 字符串是否只包含小寫字母
istitle: 字符串是否滿足title格式
isspace: 字符串是否完全由空格(包括\t制表符)組成
startswith
    "hello world".startswith("h") -->True
    "hello world".startswith("h", 1, 3) -->False 從1號索引開始到3號索引的子串是否以h開頭(截取判斷)
endswith: 和startswith用法相同

字符串的切分

splitlines: 以行切分字符串, 可以指定是否保留行標誌(0,1)
    print(
        """
            hello
            nihao
        """.splitlines(1)
    ) 
    # ['\n','    hello\n', '    nihao\n']
split: 默認以空格切分字符串,從左開始切,可以指定用來切割的字符和切分次數
rsplit: 從右切,用法同上,應用:將文件名和路徑切分開

字符串的拼接

join: 將指定的字符串插入到後面的序列的每兩個元素之間,進行拼接,形成新的字符串
    "hell".join(['1','2','3']) --》1hell2hell3
    "a".join("bcde") --> 'bacadae'
: 將指定的字符串進行重復指定次數,讀作重復
"a"
3 --》 aaa
+: 將兩個字符串拼接起來,

字符串的編碼

encode:字符到字節,可以指定編碼方式,如gbk,utf-8
decode:字節到字符,可以指定解碼方式,如gbk, utf-8

python-字符串操作分類小結