Python中字符串(str)常見操作的完整教學(xué)
對(duì)于字符串的學(xué)習(xí),我整理了網(wǎng)上的一些資料,希望可以幫助到各位?。?!
概述
由多個(gè)字母,數(shù)字,特殊字符組成的有限序列
字符串的定義:可以使用一對(duì)單引號(hào)或者雙引號(hào),也可以一對(duì)三個(gè)單引號(hào)或者一對(duì)三個(gè)雙引號(hào)定義字符串。
注意:沒有單符號(hào)的數(shù)據(jù)類型
'a' "a"
s1 = 'hello, world!' s2 = "你好,世界!" print(s1, s2) # 以三個(gè)雙引號(hào)或單引號(hào)開頭的字符串可以折行 s3 = ''' hello, world! ''' print(s3, end='')
print函數(shù)中的end=' '表示輸出后不換行,即將默認(rèn)的結(jié)束符\n(換行符)更換為' '(空字符)

創(chuàng)建字符串
#創(chuàng)建字符串 str="apple" str1='orange' print(type(str),type(str1))#<class 'str'> <class 'str'> #\轉(zhuǎn)義字符作用:讓一些符號(hào)失去原有的意義 str2 = "\"李白\"" str3 = '\'原神\'' print(str2, str3) # "李白" '原神' #定義字符串的時(shí)候,單雙引號(hào)可以互相嵌套 str4="'原神,'啟動(dòng)!??!'" print(str4) # '原神,'啟動(dòng)!??!'
拼接和重復(fù)(+、*)
s1 = 'hello' + ' ' + 'world' print(s1) # hello world s2 = '!' * 3 print(s2) # !!! s1 += s2 # s1 = s1 + s2 print(s1) # hello world!!! s1 *= 2 # s1 = s1 * 2 print(s1) # hello world!!!hello world!!!
比較運(yùn)算(ord、is、id)
字符串的比較運(yùn)算比較的是字符串的內(nèi)容
如果不清楚兩個(gè)字符對(duì)應(yīng)的編碼到底是多少,可以使用ord()函數(shù)來獲得
s1 = 'a whole new world'
s2 = 'hello world'
print(s1 == s2, s1 < s2) # False True
print(s2 == 'hello world') # True
print(s2 == 'Hello world') # False
print(s2 != 'Hello world') # True
s3 = '李白'
print(ord('李'), ord('白')) # 26446 30333
s4 = '秦始皇'
print(ord('秦'), ord('始'), ord('皇')) # 31206 22987 30343
print(s3 > s4, s3 <= s4) # False True
如果用is來比較兩個(gè)字符串,它比較的是兩個(gè)變量對(duì)應(yīng)的字符串對(duì)象的內(nèi)存地址
s1 = str(123) s2 = str(123) s3 = s2 # 比較字符串的內(nèi)容 print(id(s1))#2293238767536 print(id(s2))#2293238767584 print(id(s3))#2293238767584 print(s1 == s2, s2 == s3) # True True # 比較字符串的內(nèi)存地址 print(s1 is s2, s2 is s3) # False True
字符串特殊處理(r、f、b、u)
1、字符串前加r
r :的作用是去除轉(zhuǎn)義字符. 即如果是“\n”那么表示一個(gè)反斜杠字符,一個(gè)字母n,而不是表示換行了。 以r開頭的字符,常用于正則表達(dá)式,對(duì)應(yīng)著re模塊。 2、字符串前加f
#以f開頭表示在字符串內(nèi)支持大括號(hào)內(nèi)的python表達(dá)式
import time
name = "py小王子"
t0 = time.time()
# 這里設(shè)一些耗時(shí)操作,用sleep模擬
time.sleep(10)
print(f'{name} done in {time.time() - t0:.2f}s')
# py小王子 done in 10.00s3、字符串前加b
b:前綴表示:后面字符串是bytes類型。網(wǎng)絡(luò)編程中,服務(wù)器和瀏覽器只認(rèn)bytes類型數(shù)據(jù)。
4、字符串前加u
例:u"我是含有中文字符組成的字符串。"
后面字符串以Unicode格式進(jìn)行編碼,一般用在中文字符串前面,防止因?yàn)樵创a儲(chǔ)存格式問題,導(dǎo)致再次使用時(shí)出現(xiàn)亂碼。
成員運(yùn)算(in、not in)
s1 = 'hello, world'
print('wo' in s1) # True
s2 = 'goodbye'
print(s2 in s1) # False循環(huán)遍歷(range)
方法1、
s1 = 'hello'
for index in range(len(s1)):
print(s1[index])方法2、
s1 = 'hello'
for ch in s1:
print(ch)字符串的下標(biāo)和切片
下標(biāo):也叫索引,表示第幾個(gè)數(shù)據(jù) 在程序中,下標(biāo)一般從0開始,可以通過下標(biāo)獲取指定位置的數(shù)據(jù)
str1="welcome" print(str1[0]) #w print(str1[3]) #c
切片:從字符串中復(fù)制一段指定的內(nèi)容,生成一個(gè)新的字符串
str2 = "welcome to beijing" ''' 切片的語法: 字符串[start:end:step]截取的字符串包含開始下標(biāo)對(duì)應(yīng)的字符串 start表示開始下標(biāo)end表示結(jié)束下標(biāo) step表示步長 ''' print(str2[0:3]) # wel 包含start不包含end print(str2[1:]) # elcome to beijing 若只設(shè)置了start表示從開始下標(biāo)一直截取到最后 print(str2[:4]) # welc 若只設(shè)置了end表示從第一個(gè)字符開始一直截取到指定結(jié)束的位置 print(str2[1:4:2]) # ec # print(str2[1:4:0]) # 在切片的時(shí)候,步長不能設(shè)置為0,ValueError: slice step cannot be zero print(str2[::]) # welcome to beijing 若未設(shè)置開始和結(jié)束,表示復(fù)制字符串 print(str2[::-1]) # gnijieb ot emoclew 表示翻轉(zhuǎn)字符串 print(str2[-9:-3]) # o beij start和end若都為負(fù)數(shù),表示從右邊開始數(shù)
注意,因?yàn)樽址遣豢勺冾愋?,所以不能通過索引運(yùn)算修改字符串中的字符
獲取長度和次數(shù)(len、count)
str4 = "'原神,'啟動(dòng)?。?!'"
# 獲取字符串的長度len()
print(len(str4)) # 11
# count()在整個(gè)字符串中查找子字符串出現(xiàn)的次數(shù)
str = "電腦卡了,ss電腦呢?"
print(str.count("電腦")) # 2
# 在指定區(qū)間內(nèi)查找出現(xiàn)的次數(shù)
print(str.count("電腦", 5, 30)) # 1
字符串查找(find、rfind、index)
#find()查找子串在字符串中第一次出現(xiàn)的位置,返回的是下標(biāo),若未找到返回-1
ss3="123asdfASDCXaZ8765sahbzcd6a79"
print(ss3.find("a")) #3
print(ss3.find("y")) #-1 未找到子串,返回-1
#在指定區(qū)間內(nèi)查找
print(ss3.find("a",5,20)) #12
#rfind查找子串在字符串中最后一次出現(xiàn)的位置,返回的是下標(biāo),若未找到返回-1 print(ss3.rfind("a")) #25
print(ss3.rfind("y")) #-1
#index()功能和find類似在字符串中未找到的時(shí)候,直接報(bào)錯(cuò)
print(ss3.index("d")) #5
#print(ss3.index("y"))#ValueError:substringnotfound
#max()min()依據(jù)ASCII碼進(jìn)行的獲取print(max(ss3)) #z
print(min(ss3)) #1大小寫轉(zhuǎn)換(upper、lower、title)
#2.字符串大小寫轉(zhuǎn)換upper()lower() #upper()將字符串中的小寫字母轉(zhuǎn)換為大寫 str1="i Miss you Very Much!" print(str1.upper()) #I MISS YOU VERY MUCH! #lower()將字符串中的大寫字母轉(zhuǎn)化為小寫 print(str1.lower()) #i miss you very much! #swapcase 將字符串中的大寫轉(zhuǎn)換為小寫,將小寫轉(zhuǎn)換為大寫] print(str1.swapcase()) #I mISS YOU vERY mUCH! #title()將英文中每個(gè)單詞的首字母轉(zhuǎn)換為大寫 str2="i love you forever!" print(str2.title()) # I Love You Forever!
提取(strip)
# strip()去除字符串兩邊的指定字符(默認(rèn)去除的是空格)
ss4 = " today is a nice day "
ss5 = "***today is a nice day****"
print(ss4) # today is a nice day
print(ss4.strip()) # today is a nice day
print(ss5) # ***today is a nice day****
print(ss5.strip("*")) # today is a nice day
# lstrip只去除左邊的指定字符(默認(rèn)去除的是空格)
print(ss5.lstrip("*")) # today is a nice day****
# rstrip只去除右邊的指定字符(默認(rèn)去除的是空格)
print(ss5.rstrip("*")) # ***today is a nice day
分割和合并(split、splitlines、join)
# split()以指定字符對(duì)字符串進(jìn)行分割(默認(rèn)是空格)
ss6 = "this is a string example.....wow!"
print(ss6.split()) # 以空格進(jìn)行分割['this','is','a','string','example.....wow!']
print(ss6.split("i")) # ['th', 's ', 's a str', 'ng example.....wow!']
# splitlines()按照行切割
ss7 = '''將進(jìn)酒
君不見黃河之水天上來,奔流到海不復(fù)回.
君不見高堂明鏡悲白發(fā),************.
'''
print(ss7)
print(ss7.splitlines()) # ['將進(jìn)酒', '君不見黃河之水天上來,奔流到海不復(fù)回.', '君不見高堂明鏡悲白發(fā),************.']
# join以指定字符進(jìn)行合并字符串
ss8 = "-"
tuple1 = ("hello", "every", "body")
print(tuple1) # ['將進(jìn)酒', '君不見黃河之水天上來,奔流到海不復(fù)回.', '君不見高堂明鏡悲白發(fā),************.']
print(ss8.join(tuple1)) # hello-every-body
替換(replace)
# 替換
# replace()對(duì)字符串中的數(shù)據(jù)進(jìn)行替換
ss9 = "第五人格,啟動(dòng)?。〉谖迦烁?,真好玩?。?
print(ss9)
print(ss9.replace("第五人格", "***")) # ***,啟動(dòng)??!***,真好玩??!
# 控制替換的字符的次數(shù)
print(ss9.replace("第五人格", "***", 1)) # ***,啟動(dòng)??!第五人格,真好玩??!
判斷(isupper、islower、isdigit、istitle、isalpha)
# 字符串判斷
# isupper()檢測字符串中的字母是否全部大寫
print("ASDqwe123".isupper()) # False
print("ASD123".isupper()) # True
print()
# islower()檢測字符串中的字母是否全部小寫
print("ASDqwe123".islower()) # False
print("qwe123".islower()) # True
print()
# isdigit()檢測字符串是否只由數(shù)字組成
print("1234".isdigit()) # True
print("1234asd".isdigit()) # False
print()
# istitle()檢測字符串中的首字母是否大寫
print("Hello World".istitle()) # True
print("hello every body".istitle()) # False
print()
# isalpha()檢測字符串是否只由字母和文字組成
print("你好everyone".isalpha()) # True
print("你好everyone123".isalpha()) # False
前綴和后綴(startswith、endwith)
# 前綴和后綴:判斷字符串是否以指定字符開頭或者以指定字符結(jié)束
# startswith()判斷字符串是否以指定字符開頭
# endwith()判斷字符串是否以指定字符結(jié)束
s1 = "HelloPython"
print(s1.startswith("Hello")) # True
print(s1.endswith("thon")) # True
編解碼(encode、decode)
# encode()編碼
# decode()解碼
s2 = "hello py小王子"
print(s2.encode()) # b'hello py\xe5\xb0\x8f\xe7\x8e\x8b\xe5\xad\x90'
print(s2.encode("utf-8")) # b'hello py\xe5\xb0\x8f\xe7\x8e\x8b\xe5\xad\x90'
print(s2.encode("gbk")) # b'hello py\xd0\xa1\xcd\xf5\xd7\xd3'
# 解碼
s3 = b'hello py\xe5\xb0\x8f\xe7\x8e\x8b\xe5\xad\x90'
print(s3.decode()) # hello py小王子
ASCII碼轉(zhuǎn)換
chr() 將對(duì)應(yīng)的ASCII碼的值轉(zhuǎn)換為對(duì)應(yīng)的字符
ord() 獲取對(duì)應(yīng)字符的ASCII的值
print(chr(68)) # D
print(ord("a")) # 97格式化輸出(%)
通過%來改變后面字母或者數(shù)字的含義,%被稱為占位符
# 字符串格式化輸出
'''
%占位符
%d表示整數(shù)
%f表示小數(shù)
%s表示字符串
%.3f(表示保留3位小數(shù),保留的小數(shù)數(shù)位自己可以控制)
'''
name = "py小王子"
sex = "男"
money = 198987932.787532
print("我的姓名是:%s" % name) # 我的姓名是:py小王子
print("我的大號(hào)是%s,性別是%s,我的財(cái)富是%.2f" % (name, sex, money))
# 我的大號(hào)是py小王子,性別是男,我的財(cái)富是198987932.79
# 還可以通過f"{}{}"這種方式實(shí)現(xiàn)格式化輸出
print(f"我的大號(hào)是:{name},性別是:{sex},我的財(cái)富是{money}") # 我的大號(hào)是:py小王子,性別是:男,我的財(cái)富是198987932.787532
格式化字符串(center、ljust、rjust)
在Python中,字符串類型可以通過center、ljust、rjust方法做居中、左對(duì)齊和右對(duì)齊的處理。如果要在字符串的左側(cè)補(bǔ)零,也可以使用zfill方法。
s1 = 'hello, world'
print('wo' in s1) # True
s2 = 'goodbye'
print(s2 in s1) # False
s = 'hello, world'
# center方法以寬度20將字符串居中并在兩側(cè)填充*
print(s.center(20, '*')) # ****hello, world****
# rjust方法以寬度20將字符串右對(duì)齊并在左側(cè)填充空格
print(s.rjust(20)) # hello, world
# ljust方法以寬度20將字符串左對(duì)齊并在右側(cè)填充~
print(s.ljust(20, '~')) # hello, world~~~~~~~~
# 在字符串的左側(cè)補(bǔ)零
print('33'.zfill(5)) # 00033
print('-33'.zfill(5)) # -0033


總結(jié)
Python中操作字符串可以用拼接、切片等運(yùn)算符,也可以使用字符串類型的方法。
以上就是Python中字符串(str)常見操作的完整教學(xué)的詳細(xì)內(nèi)容,更多關(guān)于Python字符串操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中有關(guān)時(shí)間日期格式轉(zhuǎn)換問題
這篇文章主要介紹了python中有關(guān)時(shí)間日期格式轉(zhuǎn)換問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
Python子進(jìn)程subpocess原理及用法解析
這篇文章主要介紹了Python子進(jìn)程subpocess原理及用法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
tensorflow 輸出權(quán)重到csv或txt的實(shí)例
今天小編就為大家分享一篇tensorflow 輸出權(quán)重到csv或txt的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python安裝mysql-python簡明筆記(ubuntu環(huán)境)
這篇文章主要介紹了python安裝mysql-python的方法,測試環(huán)境為ubuntu,較為詳細(xì)的記錄了安裝mysql-python過程中遇到的問題與解決方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
Python 實(shí)現(xiàn)一行輸入多個(gè)值的方法
下面小編就為大家分享一篇Python 實(shí)現(xiàn)一行輸入多個(gè)值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
OpenCV-Python實(shí)現(xiàn)腐蝕與膨脹的實(shí)例
形態(tài)學(xué)操作主要包含:腐蝕,膨脹,開運(yùn)算,閉運(yùn)算,形態(tài)學(xué)梯度運(yùn)算,頂帽運(yùn)算,黑帽運(yùn)算等操作,本文主要介紹了腐蝕與膨脹,感興趣的小伙伴們可以參考一下2021-06-06
Python使用pdfminer.six實(shí)現(xiàn)精準(zhǔn)控制PDF文本布局
pdfminer.six是一款強(qiáng)大的Python庫,專注于PDF文檔的精細(xì)解析,提供字符級(jí)定位和布局控制能力,下面小編就和大家詳細(xì)介紹一下它的具體用法吧2026-04-04
使用rpclib進(jìn)行Python網(wǎng)絡(luò)編程時(shí)的注釋問題
這篇文章主要介紹了使用rpclib進(jìn)行Python網(wǎng)絡(luò)編程時(shí)的注釋問題,作者講到了自己在編寫服務(wù)器時(shí)要用unicode注釋等需要注意的地方,需要的朋友可以參考下2015-05-05

