py 字串操作方法

2021-09-27 13:32:42 字數 2951 閱讀 9664

#!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 is a good man!'))

print

(len

('tom is 一 good man!'))

'''lower(str):將str中的字母轉換成小寫字母

'''str20=

'tom is a good man'

str21=str20.lower(

)print

('str20=%s,str21=%s'

%(str20,str21)

)#upper()轉換字串中的小寫為大寫字母

str21=

'tom is a good man'

print

('的大寫是:'

,str21.upper())

print

('我是'

)#swapcase():小寫轉成大寫,大寫轉成小寫

str22=

'tom is a good man'

print

(str22.swapcase())

#capitalize:首字母大寫,其他小寫

str21=

'tom is a good man'

print

(str21.capitalize())

#title()每個單詞的首字母大寫,其他小寫

str21=

'tom is a good man'

print

(str21.title())

#center(width,fillchar):長度width,字元居中,其餘的填充fillchar字元

str21=

'tom is a good man'

print

(str21.center(30,

"-")

)#ljust(width,[fillchar]):長度width,字元居左,其餘的填充fillchar字元

str21=

'tom is a good man'

print

(str21.ljust(30,

'-')

)#rjust(width,[fillchar]):長度width,字元居右,其餘的填充fillchar字元

str21=

'tom is a good man'

print

(str21.rjust(30,

'-')

)#zfill(width):長度width,字元居右,其餘的填充0

str21=

'tom is a good man'

print

(str21.zfill(30)

)#count(str1,[stat],[end]):找個數

str21=

'tom is a good good man'

print

(str21.count(

'o')

)#4個

print

(str21.count(

'oo'))

#2個print

(str21.count(

'good'))

#2個#find(str1,[stat],[end]):找位置,沒有返回-1

str21=

'tom is a good good man'

print

(str21.find(

'oo'))

#10#rfind(str1,[stat],[end]):找位置,沒有返回-1

str21=

'tom is a good good man'

print

(str21.rfind(

'oo'))

#15#index(str1,[stat],[end]):找位置,沒有返回異常

str21=

'tom is a good good man'

print

(str21.index(

'oo'))

#10#rindex(str1,[stat],[end]):找位置,沒有返回異常

str21=

'tom is a good good man'

print

(str21.rindex(

'oo'))

#15#lstrip(fillchar):截掉左側的fillchar,預設為空格

str21=

'****tom is a good good man'

print

(str21.lstrip(

'*')

)#rstrip(fillchar):截掉右側的fillchar,預設為空格

str21=

'****tom is a good good man '

print

(str21.rstrip())

#lstrip(fillchar):截掉兩側的fillchar,預設為空格

str21=

'****tom is* a good good man****'

print

(str21.strip(

'*')

)print

(str21.strip(

))

字串操作方法

indexof 返回查詢某乙個字串第一次出現的下標 定義字串 string.indexof 要查詢的字串 從哪一下標開始 返回第一次出現的下標 slice 擷取字串兩個引數第乙個是開始的下標,第二個是結束的下標,如果第乙個引數是負數就是倒數下標。str.slice 開始的位置,結束的位置 split...

Python 字串操作方法

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

python 字串操作方法

字串物件的操作方法 序列操作方法 內建函式或表示式,如lenth 和型別特定方法 物件方法呼叫,如s.find 說明 模式 pattern 匹配是指正規表示式,re模組。而文字串分隔符就是簡單的字串。字串分割 str.split python內建函式,返回值為列表,只能傳入單一的文字串分隔符,如st...