python字符串基本操作-Python 基本字符串操作
一、字符串拼接
str.join(sequence)將序列(sequence)中的元素以指定的字符(_)連接生成一個(gè)新的字符串
a = "123"
b = "abc"
c = "ABC"
str1 = "_".join([a, b, c])
print(str1)
運(yùn)行結(jié)果:
123_abc_ABC
二、Python自定義方法
1、str.center(width[,fillchar])返回一個(gè)指定的寬度 width 居中的字符串,fillchar 為填充的字符,默認(rèn)為空格(且只能是單個(gè)字符)
str1 = "hello world!"str_center= str1.center(50, "-")print(str_center)
運(yùn)行結(jié)果:
-------------------hello world!-------------------
2、tr.endswith(suffix[,start[,end]]) 用于判斷字符串是否以指定后綴(suffix 可以是一個(gè)字符串或者是一個(gè)元素)結(jié)尾,如果以指定后綴結(jié)尾返回True,否則返回False。可選參數(shù)"start"與"end"為檢索字符串的開始與結(jié)束位置
str1 = "hello world!"
print(str1.endswith("ld!")) # 判斷str1是否以"ld!"結(jié)尾
print(str1.endswith("lo", 2, 5)) # 判斷str1中第2位開始到第5位結(jié)束的截取字符串("llo")是否以lo結(jié)尾
運(yùn)行結(jié)果:
True
True
3、str.startswith(str,beg=0,end=len(string)) 用于檢查字符串是否是以指定子字符串開頭,如果是則返回 True,否則返回 False。如果參數(shù) beg 和 end 指定值,則在指定范圍內(nèi)檢查。
str1 = "hello world!"
print(str1.startswith("hel")) # 判斷字符串("hello world!")是否以("hel")開頭
print(str1.startswith("llo", 2, 8)) # 判斷字符串("llo wo")是否以("llo")開頭
print(str1.startswith("llo", 3, 8)) # 判斷字符串("lo wor")是否以("llo")開頭
運(yùn)行結(jié)果:
True
True
False
4、str.expandtabs(tabsize=8) 把字符串中的 tab 符號(hào)(" ")轉(zhuǎn)為空格,tab 符號(hào)(" ")默認(rèn)的空格數(shù)是 8
str1 = "hello world!"
print(str1.expandtabs(20)) #制定制表符 的寬度為20
運(yùn)行結(jié)果:
hello world!
5、str.find(str,beg=0,end=len(string)) 檢測(cè)字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結(jié)束) 范圍,則檢查是否包含在指定范圍內(nèi),如果包含子字符串返回開始的索引值,否則返回-1
str1 = "hello world!"
print(str1.find("w")) #查找指定的元素("w")的第一個(gè)索引值并返回
print(str1.find("g")) #查找的元素不存在返回-1
運(yùn)行結(jié)果:
6
-1
6、str.format()Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強(qiáng)了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 %;可以接受不限個(gè)參數(shù),位置可以不按順序
str1 = "hello world, {name} is {age}"
print(str1.format(name="Quincy", age=29)) #格式化輸出
dic1 = {"name": "Python", "age": "15"}print(str1.format(**dic1)) #通過字典設(shè)置參數(shù)
運(yùn)行結(jié)果:
hello world, Quincy is 29hello world, Pythonis 15
7、str.index(str,beg=0,end=len(string)) 檢測(cè)字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結(jié)束) 范圍,則檢查是否包含在指定范圍內(nèi),該方法與 python find()方法一樣,只不過如果str不在 string中會(huì)報(bào)一個(gè)異常
str1 = "hello world!"
print(""el"在字符串str1中的位置是:%d" % str1.index("el"))
運(yùn)行結(jié)果:
"el"在字符串str1中的位置是:1
查詢索引失敗報(bào)異常:
str1 = "hello world!"
print(str1.index("gg"))
Traceback (most recent call last):
File "C:/Python_Learning/PyFullStack/Week2/Day1/String_1.py", line 43, in
print(str1.index("gg"))
ValueError: substring not found
8、str.isalnum() 檢測(cè)字符串是否由字母和數(shù)字組成
str2 = "abc1234"str3= "abc_1234"
print(str2.isalnum()) #判斷是否為字母或數(shù)字
print(str3.isalnum())
運(yùn)行結(jié)果:
True
False
9、str.isdecimal()檢查字符串是否只包含十進(jìn)制字符。這種方法只存在于unicode對(duì)象(注意:定義一個(gè)十進(jìn)制字符串,只需要在字符串前添加 "u" 前綴即可),
如果字符串是否只包含十進(jìn)制字符返回True,否則返回False。
str4 = u"12345"str5= u"12345abc"
print(str4.isdecimal()) #判斷是否為十進(jìn)制數(shù)字
print(str5.isdecimal())
運(yùn)行結(jié)果:
True
False
10、str.isalpha() 檢測(cè)字符串是否只由字母組成,如果字符串至少有一個(gè)字符并且所有字符都是字母則返回 True,否則返回 False
str6 = "PythonIsFun"
str7 = "Python Is Fun"
str8 = "Python3"
print(str6.isalpha()) # 檢測(cè)字符串是否只由字母組
print(str7.isalpha())
print(str8.isalpha())
print("".isalpha())
運(yùn)行結(jié)果:
True
False
False
False
11、str.isidentifier() 用于判斷字符串是否是有效的 Python 標(biāo)識(shí)符,可用來判斷變量名是否合法,如果字符串是有效的 Python 標(biāo)識(shí)符返回 True,否則返回 False
#判斷字符串是否是有效的 Python 標(biāo)識(shí)符,可用來判斷變量名是否合法
print("if".isidentifier()) #True
print("def".isidentifier()) #True
print("class".isidentifier()) #True
print("_a".isidentifier()) #True
print("中國(guó)123a".isidentifier()) #True
print("123".isidentifier()) #False
print("3a".isidentifier()) #False
print("".isidentifier()) #False
運(yùn)行結(jié)果:
True
True
True
True
True
False
False
False
12、str.islower() 檢測(cè)字符串是否由小寫字母組成,如果字符串中包含至少一個(gè)區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是小寫,則返回 True,否則返回 False
print("abc".islower())
print("Abc".islower())
print("123bc".islower())
運(yùn)行結(jié)果:
True
False
True
13、str.isupper() 檢測(cè)字符串中所有的字母是否都為大寫,如果字符串中包含至少一個(gè)區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是大寫,則返回 True,否則返回 False
print("ABC".isupper())print("Abc".isupper())print("A123".isupper())
運(yùn)行結(jié)果:
True
False
True
14、str.isspace() 檢測(cè)字符串是否只由空格組成,如果字符串中只包含空格,則返回 True,否則返回 False
print(" ".isspace()) #判斷字符串是否為空格
print("This is a test".isspace()) #判斷字符串是否為空格
運(yùn)行結(jié)果:
True
False
15、str.istitle() 檢測(cè)字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫,如果字符串中所有的單詞拼寫首字母為大寫,且其他字母為小寫則返回 True,否則返回 False
str1 = "This Is String Example"str2= "This is String example"
print(str1.istitle()) #檢測(cè)字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫
print(str2.istitle()) #檢測(cè)字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫
運(yùn)行結(jié)果:
True
False
16、str.isnumeric() 檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象(注:定義一個(gè)字符串為Unicode,只需要在字符串前添加 "u" 前綴即可)
str1 = u"this2009"str2= u"20090728"
print(str1.isnumeric()) #檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象
print(str2.isnumeric()) #檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象
運(yùn)行結(jié)果:
False
True
17、str.lower() 轉(zhuǎn)換字符串中所有大寫字符為小寫
str1 = "THIS IS STRING EXAMPLE"str2= "This is String example"
print(str1.lower())print(str2.lower())
運(yùn)行結(jié)果:
this isstring example
thisis string example
18、str.upper() 將字符串中的小寫字母轉(zhuǎn)為大寫字母
str1 = "this is string example"
str2 = "This Is String Example"
print(str1.upper())
print(str2.upper())
運(yùn)行結(jié)果:
THIS IS STRING EXAMPLE
THIS IS STRING EXAMPLE
19、str.swapcase() 用于對(duì)字符串的大小寫字母進(jìn)行轉(zhuǎn)換
str1 = "this is string example"str2= "This Is String Example"
print(str1.swapcase()) #大小寫反轉(zhuǎn)
print(str2.swapcase()) #大小寫反轉(zhuǎn)
運(yùn)行結(jié)果:
THIS IS STRING EXAMPLE
tHIS iS sTRING eXAMPLE
20、str.ljust(width[,fillchar]) 返回一個(gè)原字符串左對(duì)齊,并使用空格填充至指定長(zhǎng)度的新字符串。如果指定的長(zhǎng)度小于原字符串的長(zhǎng)度則返回原字符串
print("Progress:80%".ljust(80, "*"))
運(yùn)行結(jié)果:
Progress:80% *******************************************************************
21、str.rjust(width[,fillchar]) 返回一個(gè)原字符串右對(duì)齊,并使用空格填充至長(zhǎng)度 width 的新字符串。如果指定的長(zhǎng)度小于字符串的長(zhǎng)度則返回原字符串
print("Progress:80%".rjust(80, "-"))
運(yùn)行結(jié)果:
--------------------------------------------------------------------Progress:80%
22、str.strip([chars]) 用于移除字符串頭尾指定的字符(默認(rèn)為空格或換行符)或字符序列(注意:該方法只能刪除開頭或是結(jié)尾的字符,不能刪除中間部分的字符)
str1 = "ymy lovely baby girl y"
print(str1.strip("y")) # 用于移除字符串頭尾指定的字符(默認(rèn)為空格或換行符)或字符序列
運(yùn)行結(jié)果:
my lovely baby girl
23、str.lstrip([chars]) 用于截掉字符串左邊的空格或指定字符
str.rstrip([chars]) 刪除 string 字符串末尾的指定字符(默認(rèn)為空格)
str1 = "ymy lovely baby girl y"
print(str1.lstrip("y")) #用于截掉字符串左邊的空格或指定字符
print(str1.rstrip("y")) #用于截掉字符串末尾的空格或指定字符
運(yùn)行結(jié)果:
my lovely baby girl y
ymy lovely baby girl
24、str.split(str="",num=string.count(str)) 通過指定分隔符對(duì)字符串進(jìn)行切片,如果參數(shù) num(分割次數(shù)。默認(rèn)為 -1, 即分隔所有)有指定值,則分隔 num+1 個(gè)子字符串(str默認(rèn)為所有的空字符,包括空格、換行( )、制表符( )等)
str1 = "Hello, This is a string test."
print(str1.split()) #以默認(rèn)空格符進(jìn)行分割
print(str1.split(" ", 2)) #以空格符進(jìn)行分割2+1次
print(str1.split(",")) #以制定字符","進(jìn)行分割
運(yùn)行結(jié)果:
["Hello,", "This", "is", "a", "string", "test."]
["Hello,", "This", "is a string test."]
["Hello", "This is a string test."]
25、str.rsplit(str="",num=string.count(str)) 類似于split,區(qū)別是從字符串最后面開始分割
str1 = "Hello, This is a string test, I like Python."
print(str1.rsplit()) # 以默認(rèn)空格符從最后面開始進(jìn)行分割
print(str1.rsplit(" ", 2)) # 以空格符從最后面開始進(jìn)行分割2+1次
print(str1.rsplit(",", 1)) # 以制定字符","從最后面開始進(jìn)行分割
運(yùn)行結(jié)果:
["Hello,", "This", "is", "a", "string", "test,", "I", "like", "Python."]
["Hello, This is a string test, I", "like", "Python."]
["Hello, This is a string test", "I like Python."]
26、str.rfind(str,beg=0end=len(string)) 返回字符串最后一次出現(xiàn)的位置(從右向左查詢),如果沒有匹配項(xiàng)則返回-1
str1 = "This is a string test"
print(str1.rfind("s")) #返回字符串最后一次出現(xiàn)s的位置(從右向左查詢),如果沒有匹配項(xiàng)則返回-1
運(yùn)行結(jié)果:
19
27、str.title()返回"標(biāo)題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫(見 istitle())
str1 = "this is a string test"
print(str1.title()) #字符串首字母大寫
運(yùn)行結(jié)果:
This Is A String Test
總結(jié)
以上是生活随笔為你收集整理的python字符串基本操作-Python 基本字符串操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 装修发票的税率是多少
- 下一篇: rstudio python_如虎添翼: