字符串(string)
1.拼接字符串
str1 = '秦始皇'
str2 = '中國'
print(str1 + '----' + str2)
結果:
秦始皇----中國
2.計算字符串長度
在Python中:
英文、數字、小數點、下劃線和空格佔1個字節;
漢字在GBK / GB2312編碼格式中佔2個字節,在UTF-8 / Unicode編碼中一般佔用3個字節。
但是默認情況下計算字符串長度時,不區分英文、漢字和數字,統統按1個字符計算。
如下所示:
str = '人生苦短,我用Python'
print(len(str))
結果:
13
當指定UTF-8編碼時,如下:
str = '人生苦短,我用Python'
print(len(str.encode())) # UTF-8編碼
結果:
27
當指定GBK編碼時,如下:
str = '人生苦短,我用Python'
print(len(str.encode('gbk'))) # GBK編碼
結果:
20
3.截取字符串
語法:string[start: end: step]
str = '人生苦短,我用Python'
print(str[0: 15: 2])
結果:
人苦,用yhn
4.分割字符串
str.split(sep, maxsplit)
str: 要分割的字符串
sep: 指定分隔符,可以包含多個字符,默認爲None,即所有空字符(包括空格、換行符’\n’,製表符’\t’等)
maxsplit: 可選參數,指定分割次數,如果不指定或者爲-1,則分割次數沒有限制,否則返回結果列表的元素個數,個數最多爲maxsplit + 1
(1)如果不指定分割符,且字符串中沒有默認的分割符,結果會輸出原字符串
str = '人生苦短,我用Python'
a = str.split()
print(a)
結果:
['人生苦短,我用Python']
(2)如果不指定分割符,字符串中有默認的分割符,結果會進行分割
str = '人 生 苦 短 ,我 用Python'
a = str.split()
print(a)
結果:
['人', '生', '苦', '短', ',我', '用Python']
(3)如果指定分割符,結果會進行分割
str = '人生苦短,我用Python'
a = str.split(',')
print(a)
結果:
['人生苦短', '我用Python']
默認採用空白符進行分割
5.合併字符串
字符串的合併和字符串的拼接不同,字符串的合併會將字符串按照固定的分割符拼接在一起,字符串的拼接只是純粹的使用“+”將字符串連接在一起。
語法:new_str = a.join(iterable)
new_str:合併後的新字符串
a:拼接符,屬於字符串類型,書寫時記得帶上引號
iterable:可迭代對象
list = ['中國', '俄羅斯', '以色列', '南非']
str = 'and &'.join(list)
print(str)
結果:
中國and &俄羅斯and &以色列and &南非
6.檢索字符串
(1)count()
語法:str.count(sub)
str:原字符串
sub:要檢索的子字符串
str = 'i am a student, he is also a student'
a = str.count('student')
print(a)
結果:
2
(2)find()
檢索是否包含指定的字符串,如果檢索的字符串不存在,返回-1,如果存在,則返回首次出現該字符串的索引。
語法:str.find(sub)
str = 'i am a student, he is also a student'
a = str.find('b')
print(a)
結果:
-1
以上代碼因爲原字符串不包含字符串b,所以返回-1。
str = 'i am a student, he is also a student'
a = str.find('a')
print(a)
結果:
2
以上代碼因爲原字符串包含字符串a,所以返回首次出現該字符串的索引值。
還有一個rfind()方法,與find()方法類似,只不過rfind()方法是從字符串右邊開始查找。
(3)in/not in
判斷是否包含某段字符串還可以用in / not in來判斷,返回結果是布爾類型的True或者False
語法:子字符串 in 字符串
str = 'i am a student, he is also a student'
print('student' in str)
結果:
True
(4)index()
index()方法與find()方法類似,都是用來查找是否包含某段字符串,只不過index()方法當某段字符串不存在時,會拋出異常。
語法:str.index(sub)
首先來看某段字符串存在時:
str = 'i am a student, he is also a student'
a = str.index('he')
print(a)
結果:
16
其次,看下某段字符串不存在時:
Traceback (most recent call last):
File "C:/Users/admin/Desktop/python_basic/homework/homework1.py", line 2, in <module>
a = str.index('hello')
ValueError: substring not found
(5)startswith()
檢索字符串是否以指定的子字符串開頭,如果是返回True,如果不是返回False。
語法:str.startswith(sub)
str:原字符串
sub:要檢索的子字符串
str = 'i am a student, he is also a student'
a = str.startswith('i')
print(a)
結果:
True
注意:這個單詞是startswith(),不是startwith(),中間還有一個s,下面endswith()同理
(6)endswith()
檢索字符串是否以指定的子字符串結尾,如果是返回True,如果不是返回False。
語法:str.endswith(sub)
str:原字符串
sub:要檢索的子字符串
str = 'i am a student, he is also a student'
a = str.endswith('udent')
print(a)
結果:
True
7.字母的大小寫轉換
(1)lower()
語法:str.lower()
str = 'I am a STUDENT, he is also a student'
a = str.lower()
print(a)
結果:
i am a student, he is also a student
(2)upper()
語法:str.upper()
str = 'I am a STUDENT, he is also a student'
a = str.upper()
print(a)
結果:
I AM A STUDENT, HE IS ALSO A STUDENT
8.去除字符串中的空格和特殊的字符
(1)strip()
去除字符串左右兩邊的空格和特殊字符。
語法:str.strip([chars])
str:原字符串
chars:可選參數,去除指定的字符,可以指定多個。如果指定參數,則去除所指定的參數;如果沒有指定參數,則默認去除空格、製表符\t,回車符\r,換行符\n
首先不設置參數:
str = ' @@..$I am a STUDENT, he is also a student..() \t'
a = str.strip()
print(a)
結果:
@@..$I am a STUDENT, he is also a student..()
其次,設置參數:
str = ' @@..$I am a STUDENT, he is also a student..() \t'
a = str.strip(' @.$()\t')
print(a)
結果:
I am a STUDENT, he is also a student
(2)lstrip()
去除字符串左邊的空格和特殊字符
語法同strip()類似
str = ' @@..$I am a STUDENT, he is also a student..() '
a = str.lstrip(' @.$()\t')
print(a)
結果:
I am a STUDENT, he is also a student..() *
(3)rstrip()
去除字符串右邊的空格和特殊字符
語法同strip()類似
str = ' @@..$I am a STUDENT, he is also a student..() *'
a = str.rstrip(' .()*')
print(a)
結果:
@@..$I am a STUDENT, he is also a student
9.格式化字符串
(1)使用%操作符
(2)format()
語法:str.format(args)
str:原字符串
args:指定要轉換的項,如果有多項,則用逗號進行分隔。
1)字段名字爲整數,表示參數的位置
print("my name is {0} and my age is {1} years old".format('sunlin', '100'))
輸出:
my name is sunlin and my age is 100 years old
2)字段名字爲參數的名字
print("my name is {mingzi} and my age is {nianling} years old".format(mingzi = 'sunlin', nianling = '100'))
輸出:
my name is sunlin and my age is 100 years old
3)列表的取值
print("my name is {0[0]} and my age is {0[1]} years old".format(['sunlin', 100]))
print("my name is {[1]} and my age is {[2]}".format(['sunlin', 'dagou', 'ergou'], [21, 34, 47]))
輸出:
my name is sunlin and my age is 100 years old my name is dagou and my
age is 47
4)字典的取值
infor = {'ming_zi': 'sunlin', 'nian_ling': '24'}
print("my name is {ming_zi} and my age is {nian_ling}".format(**infor))
輸出:
my name is sunlin and my age is 24
10.替換字符串 replace()
語法:str.replace(‘要替換的子字符串’, ‘替換的符號’)
str = '中國共產黨'
a = str.replace('共產黨', '*')
print(a)
結果:
中國*