1. 程式人生 > >Python----字符串常用方法總結

Python----字符串常用方法總結

www. str 分割 符號 split() 取字符 -- num int

字符串可以存任意類型的字符串,比如字母,名字,一句話等等。

name = python

tag = Welcome to china!

字符串還有很多內置的方法,對字符串進行操作,常用的方法如下,下面註釋帶有是否的,返回的都是一個布爾值
1、去掉空格和特殊符號

a=   字 符 串    \n\n\n\n\n

a.strip()  #默認去掉字符串兩邊的空格和換行符

a.lstrip()  #默認去掉字符串左邊的空格和換行符

a.rstrip() #默認去掉字符串右邊的空格

2、字符串的查詢和替換

address = http://www.nnzHp.cn

wold 
= day is a wondefual day! print(wold.strip(day)) #如果strip方法指定一個值的話,那麽會去掉這兩個值 print(wold.count(a)) #統計字符串出現的次數 print(wold.index(z)) #找到這個字符返回下標,多個時返回第一個;,如果元素找不到的話,會報錯 print(wold.find(z)) #找到這個字符返回下標,多個時返回第一個;,如果元素找不到的話,返回-1 print(wold.replace(day,DAY)) #替換字符串 print(wold.isdigit()) #
判斷字符串是否為純數字 print(address.startswith(http)) #判斷是否以某個字符串開頭 print(address.endswith(.jpg)) #判斷是否以某個字符串結尾 print(wold.upper()) #變成大寫的 print(wold.lower()) #變成小寫的 print(wold.capitalize()) #首字母大寫

3、字符串的測試和替換函數

word.startswith(prefix[,start[,end]])  #是否以prefix開頭 

word.endswith(suffix[,start[,end]])  
#以suffix結尾 word.isalnum() #是否全是字母和數字,並至少有一個字符 word.isalpha() #是否全是字母,並至少有一個字符 word.isdigit() #是否全是數字,並至少有一個字符 word.isspace() #是否全是空白字符,並至少有一個字符 word.islower() #word中的字母是否全是小寫 word.isupper() #word中的字母是否便是大寫 word.istitle() #word是否是首字母大寫的

4、字符串的分割,使用.split()方法:通過該字符串中已存在的某個字符串,分割該字符串,什麽也不傳的話,是以空格分割的

names=abcd

name_list = names.split(b)  #根據某個字符串,分割字符串,什麽也不傳的話,是以空格分割的

#打印結果為:[‘a‘, ‘cd‘]  #以字母b分割,則b不再顯示

5、連接字符串,‘ ‘.join()方法1.它把一個list變成了字符串;2.通過某個字符串把list裏面的每個元素連接起來;3.只要是可以循環的,join都可以幫你連起來

l=[zhang,liu,liang]

res = ‘‘.join(l)

#打印結果為:zhangliuliang

l=[zhang,liu,liang]

res = ,.join(string.ascii_lowercase)#用,把所有小寫字母連起來

#打印結果為:a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

6、字符串切片

str = 0123456789′

print str[0:3]  #截取第一位到第三位的字符

print str[:]  #截取字符串的全部字符

print str[6:]  #截取第七個字符到結尾

print str[:-3]  #截取從頭開始到倒數第三個字符之前

print str[2]  #截取第三個字符

print str[-1]  #截取倒數第一個字符

print str[::-1]  #創造一個與原字符串順序相反的字符串

print str[-3:-1]  #截取倒數第三位與倒數第一位之前的字符

print str[-3:]  #截取倒數第三位到結尾

print str[:-5:-3]  #逆序截取

7、string模塊

string.ascii_uppercase  #所有大寫字母

string.ascii_lowercase  #所有小寫字母

string.ascii_letters  #所有字母

string.digits  #所有數字

Python----字符串常用方法總結