py 字串操作

2021-10-05 18:29:05 字數 1010 閱讀 8202

基本的操作

a =

'helle'

,b =

'world'

'hello'*2

#兩遍hello

'helloworld'[2

:]#結果為lloworld

'el'

in'hello'

#在,true

c = a+b #字串的連線,但是更推薦用join

string的常用內建方法:

c =

'hello world '

'--'

.join(

[a,b]

)#用--連線字串ab

c.count(

'e')

#計算e出現次數

c.center(20,

'*')

#居中,************hello world**************

c.startswith(

'he'

)#判斷c是否以he開頭

c.endswith(

'aaa'

)#判斷是否以aaa結尾

c.find(

't')

#查詢首個t位置,若存在,則返回索引值,否則返回-1

c.format

(name =

'aintdone'

)#hello world aintdone

c.format_map(

)#()裡用字典

c.lower(

)c.upper(

)

c.replace(

'helle'

,'****',1

)#c變為**** world

c.spilt(

' ')

#分割字串為列表,''.join()可以將列表變為字串

c.strip(

)#去掉字串開頭與結尾的空格,換行符等

py 字串操作方法

coding utf 8 eval str 將字串當成有效的表示式,並返回結果,相當與int num1 eval 123 print num1 print type num1 print eval 12 3 print eval 123 len str 返回字串的長度 print len tom i...

py字串的索引,切片等其他操作

字串的索引 s qwertyui 索引時取字串的下標即可,下標以0開始 例 ss s 3 列印出來的是r ss s 1 列印出來的是i 字串的切片顧頭不顧尾 ss s 0 3 列印出來的是qwe ss s 0 1 列印出來的是qwertyu ss s 0 s 全部列印 ss s 0 0 什麼打不列印...

Py 字串方法及注釋

capitalize 把字串的第乙個字元改為大寫 casefold 把整個字串的所有字元改為小寫 center width 將字串居中,並使用空格填充至長度 width 的新字串 count sub start end 返回 sub 在字串裡邊出現的次數,start 和 end 引數表示範圍,可選。...