標籤:對齊 int 置中 參數 應用 去除 位元組 swa cab
1、切片操作:
str[start:end:step]
包括頭,不包括尾巴
step為步長,意思是每隔step-1個元素,取一個字元
"while"[::-1] 反向取字串,實現字串的反轉--》"elihw"
2、方法:
字串的修飾:
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:
len 方法返回指定序列的長度
字串的尋找:
count:計數功能,返回指定字元在字串中的個數
"hello".count(‘l‘) -->2
find:尋找,返回從左往右第一個指定字元的索引,如果找不到則返回-1
"hello".find(‘l‘) --》2
rfind: 尋找,返回從右往左第一個指定字元的索引
index: 和find效果一樣,區別在於,找不到則報錯
rindex: 和rfind效果一樣,區別在於,找不到則報錯
字串的替換:
replace:從左至右替換指定的元素,可以指定替換的個數,預設全部替換
"helllo".replace("l", "L") 將所有的l替換為L
"helllo".replace("l", "L", 2) 將l替換為L,只替換2個
translate: 按照對應關係來替換內容
from string import maketrans
trans = maketrans("12345", "abcde")
"12123123".translate(trans) -->ababcabc
字串的變形:
upper:將字串當中所有的字元轉化為大寫
"While".upper() --》 WHILE
lower:將字串當中所有的字元轉化為小寫
"While".upper() --》 while
swapcase: 將字串當中所有的字元大小寫進行反轉
"While".upper() --》 wHILE
title: 將字串當中的單字首大寫,單詞以空格劃分
"While is ok ".upper() --》 While Is Ok
capitalize: 只有字串的首字元大寫
"while IS ok ".upper() --》 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字串操作分類總結