python3字串常用的方法

2022-09-12 20:36:24 字數 1348 閱讀 7529

以指定的字元拆分原字串並重組乙個新的字串,如下:在每個字元插入空格

old_str = "

窗前明月光,疑似地上霜

"new_str = "

".join(old_str)

去除字串兩邊的空格,還可以去除製表符 \t  換行符 \n 等特殊字元

此外還有只去除左邊或右邊的 lstrip() 和rstrip()

my_str  = "

\t你好\t\n

"my_str = my_str.strip()

按照指定的字元分割成列表,不包含被分割的字元。如下:0和23是起止位,可不寫

sp_str = "

abcdefg,abcdefg,abcdefg

"sp_str = sp_str.split("

,", 0, 23)

將字串全部轉換成小寫

lo_str = "

abcdeg

"lo_str = lo_str.lower()

將字串全部轉換成大寫

up_str = "

abhefgk

"up_str = up_str.upper()

查詢指定的字串子串並返回該字串子串所在的索引值,若找不到返回-1,帶數字引數則為起止位置查詢,可不帶

fd_str = "

iamxiaoming

"result = fd_str.find("

xiao

",0,11)

替換指定字串的子字串內容或者替換字串內容,帶數字引數則為起止位置和執行的次數,可不帶

re_str = "

小明是乙個二年級學生

"re_str = re_str.replace("

二年級","

初中",0,9)

字串格式化填充

template = "

小明是一位,今年歲了,在上學

"result = template.format("

小學生",11,"

陽光小學

")

template = "

小明是一位,在工作

"result = template.format(work="

工人",address="

廣州")

或者用format_map()

template = "

小明是一位,在工作

"result = template.format_map()

python3 字串方法

1 join方法 test nancy v join test print v 執行結果 n a n c y 2 split方法 不帶引數時,字串以空格 n t進行分割 例子 test1 nancy alex tim t james nfigo v1 test1.split print v1 執行結...

python3 字串常用操作

name my name is lisi 首字母大寫 capitalize name.capitalize my name is lisi 字串全部大寫 upper name.upper my name is lisi 字串全部小寫 lower name.lower my name is lisi ...

python3字串方法總結

1 capitalize 將字串的第乙個字元轉換為大寫 2center width,fillchar 返回乙個指定的寬度 width 居中的字串,fillchar 為填充的字元,預設為空格。3count str,beg 0,end len string 返回 str 在 string 裡面出現的次數...