str 字串 常用內建函式

2022-08-23 15:09:10 字數 2678 閱讀 4464

列舉了幾個重要的字串操作常用內建函式

1

#s.replace(old,new[,count])2#

替換字串裡的字元,old為要被替換的,new為替換的;3#

count為指定替換次數,不寫替換所有

45 s = '

hello world'6

7print (s.replace('

o','d'

))8print (s.replace('

o','

d',1))

輸出:

helld wdrld

helld world

1

#s.find(sub[,start[,end]]) -->int2#

查詢是否包含sub,start(選填)起始索引,end結束索引3#

只會顯示左邊第乙個

45 s = "

hello world"6

7print (s.find('o'

))8print (s.find('

o', 5))

9print (s.find('

o', 1, 7))

輸出:

4

74

1

#s.count(sub[, start[, end]]) -> int2#

用於統計字串裡某個字元出現的次數3#

sub為子字串,start起始索引位置,預設0;end結束索引位置(不包含)

45 s = '

hello world'6

7print (s.count('o'

))8print (s.count('

o', 4, 7))

輸出:

2

1

#

s.strip([chars]) -> str

#移除字串頭尾指定的字元

#預設移除空格,可指定字元

#

s.center(width[, fillchar]) -> str

#指定的寬度 width 居中的字串,fillchar 為填充的字元,預設為空格

#width為字串總寬度

s = '

hello world

print (s.center(50, '

-'))

輸出:

-------------------hello world--------------------

#

s.split(sep=none, maxsplit=-1) -> list of strings

#將字串切片

#sep 指定分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等

#maxsplit 指定最大切片次數

s = '

hello world ding

'print

(s.split())

print (s.split("

",1))

輸出:

['hello', 'world', 'ding']

['hello', 'world ding']

#

格式化字串

#基本語法是通過 {} 和 : 來代替以前的 %

#用法一

>>>"

{} {}

".format("

hello

", "

world

") #

不設定指定位置,按預設順序

'hello world'

>>> "

".format("

hello

", "

world

") #

設定指定位置

'hello world'

>>> "

".format("

hello

", "

world

") #

設定指定位置

'world hello world'#

用法二print("

".format(name="

電影", url="

www.beiwo.tv"))

#通過字典設定引數

site =

print("

".format(**site)) #

』**『這裡指引用key

#通過列表索引設定引數

my_list = ['

電影', '

www.beiwo.tv']

print("

".format(my_list)) #

"0" 是必須的

方法二輸出:

1

#s.join(iterable) -> str2#

將序列中的元素以指定的字元連線生成乙個新的字串3#

s為連線符4#

括號內指定要鏈結的字串序列

56 s = '

hello world'7

8print ('

-'.join(s))

輸出:

h-e-l-l-o- -w-o-r-l-d

Python字串常用內建函式

序號 方法及描述 1capitalize 將字串的第乙個字元轉換為大寫 2center width,fillchar 返回乙個指定的寬度 width 居中的字串,fillchar 為填充的字元,預設為空格。3count str,beg 0,end len string 返回 str 在 string...

字串內建函式

方法 描述 string.capitalize 把字串的第乙個字元大寫 string.center width 返回乙個原字串居中,並使用空格填充至長度 width 的新字串 string.count str,beg 0,end len string 返回 str 在 string 裡面出現的次數,...

字串內建函式

string.capitalize 把字串的第乙個字元大寫 string.center width 返回乙個原字串劇中,並使用空格填充至長度width的新字串 string.count str,beg 0,end len string 返回str在string裡面出現的引數,如果beg或者end指定...