字符串是程序中最常用的數據類型之一,它們用於不同的任務,例如從數據庫中檢索數據、在GUI應用程序中創建標籤和按鈕以及生成文本分析結果。Python中提供了豐富的字符串操作函數和方法,本文將系統地介紹它們。
一、字符串的基本操作
1、字符串的定義和賦值
'''Python字符串''' # 定義一個空字符串
str = 'hello, world!' # 定義一個有值的字符串
2、字符串的索引和切片
str = 'hello, world!'
print(str[0]) # 輸出h
print(str[-1]) # 輸出!
print(str[0:5]) # 輸出 hello
3、字符串的拼接
str1 = 'hello'
str2 = 'world'
print(str1 + str2) # 輸出 hello world
二、字符串的常用方法
1、字符串的長度
str = 'hello, world!'
print(len(str)) # 輸出13
2、字符串的查找
str = 'hello, world!'
print(str.find('l')) # 輸出2,查找第一個字符l出現的位置
print(str.find('l', 3)) # 輸出3,從第3個位置開始查找字符l出現的位置
print(str.find('x')) # 輸出-1,查不到返回-1
print(str.index('l')) # 輸出2,查找第一個字符l出現的位置
print(str.index('l', 3)) # 輸出3,從第3個位置開始查找字符l出現的位置
# print(str.index('x')) # 輸出異常,查不到會拋出異常
3、字符串的替換
str = 'hello, world!'
print(str.replace('world', 'python')) # 輸出 hello, python!
4、字符串的分裂和連接
str = 'hello, world!'
print(str.split(', ')) # 輸出['hello', 'world!']
strList = ['hello', 'world!']
print(', '.join(strList)) # 輸出 hello, world!
5、字符串的大小寫轉換
str = 'hello, world!'
print(str.upper()) # 輸出HELLO, WORLD!
print(str.lower()) # 輸出hello, world!
print(str.capitalize()) # 輸出Hello, world!
三、正則表達式
正則表達式是一種用於模式匹配的文本字符串,它是用單個字符串描述匹配一組或者多組字符串的方法。Python內置了re模塊,提供了實現正則表達式的功能。
1、re.findall方法:匹配所有滿足條件的字符串
import re
s = 'hello world!'
lst = re.findall('o', s) # 匹配所有的'o'
print(lst) # 輸出['o', 'o']
2、re.search方法:從字符串開頭匹配第一個滿足條件的字符串
import re
s = 'hello world!'
lst = re.search('l..l', s) # 匹配'l..l'
print(lst.span()) # 輸出(2, 6)
3、re.sub方法:替換匹配到的字符串
import re
s = 'hello world!'
new_str = re.sub('world', 'python', s) # 將world替換為python
print(new_str) # 輸出 hello python!
四、unicode編碼與字符串轉換
Python3中默認的字符串編碼格式是Unicode編碼。字符串和unicode之間可以通過encode和decode方法進行轉換。
1、字符串轉換為Unicode編碼
str = 'hello, world!'
new_str = str.encode('UTF-8')
print(type(new_str)) # 輸出 <class 'bytes'>
print(new_str) # 輸出 b'hello, world!'
2、Unicode編碼轉換為字符串
str = b'hello, world!'
new_str = str.decode('UTF-8')
print(type(new_str)) # 輸出 <class 'str'>
print(new_str) # 輸出hello, world!
總結
Python字符串操作是編程中必不可少的一部分,希望這篇文章能夠讓大家更加深入理解Python字符串的基本操作、常用方法、正則表達式和Unicode編碼等方面,為日後的編程工作提供幫助。
原創文章,作者:KXUJK,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/329175.html