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