第六章 字符串和正則表達式
字符串是開發程序中最常見的數據類型,字符串得到處理實際應用中經常面對的問題。Python
提供了功能強大的字符串模塊,正則表達式專門用於匹配程序中的數據,能夠簡化字符串的處理程序。
6.1 常見的字符串操作
字符串是python
的一種基本類型,字符串的操作包括字符串的格式化,字符串的截取,過濾,合併和查找等操作。
使用%f
可以格式浮點數的精度,根據指定的精度做四捨五入。
#帶精度的格式化
print ("浮點型數字: %f" % 1.25) #以浮點數格式打印
print ("浮點型數字: %.1f" % 1.25) #精確到小數點後一位
print ("浮點型數字: %.2f" % 1.254) #精確到小數點後兩位
如果要在字符串中輸入%
,需要使用%%
。Python
可以實現字符串的對齊操作。
#字符串對齊
word = "version3.0"
print (word.center(20))
print (word.center(20, "*"))
print (word.ljust(20))
print (word.rjust(20))
print ("%30s" % word)
代碼中的“20”表示一共輸出20個字符。ljust
表示左對齊,rjust
表示右對齊。%30s
表示先輸出30個空格。python
使用\
作爲轉義字符。
# 輸出轉義字符
path = "hello\tworld\n"
print (path)
print (len(path))
path = r"hello\tworld\n"
print (path)
print (len(path))
Python
還提供了函數strip()
,lstrip()
,rstrip()
,去掉轉義字符串中的轉義符。
# strip()去掉轉義字符
word = "\thello world\n"
print ("直接輸出:", word)
print ("strip()後輸出:", word.strip())
print ("lstrip()後輸出:", word.lstrip())
print ("rstrip()後輸出:", word.rstrip())
python
使用“+
”連接不同的字符串。python
會根據“+
”兩側變量的類型,決定執行連接操作或是加法運算。如果兩側爲字符串類型,則進行連接操作;如果兩側都是數字類型,則進行加法運算;如果兩側是不同的類型,將拋出異常。
# 使用"+"連接字符串
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print (result)
python
提供了函數join()
連接字符串,配合列表可以實現多個字符串的連接。
# 使用join()連接字符串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print (result)
字符串的截取是實際應用中最常用的技術,被截取的部分稱爲“子串”。如果同時截取多個子串,可以使用函數split()
實現。
split ([char] [,num])
參數char
表示用於分割的字符(變量名),默認的分割字符是空格。參數num
表示分割的次數。如果num
等於2,將把源字符串分割爲3個子串。字符串連接後,python
將分割新的空間給連接後的字符串,源字符串保持不變。
# 使用split()獲取子串
sentence = "Bob said: 1, 2, 3, 4"
print ("使用空格取子串:", sentence.split())
print ("使用逗號取子串:", sentence.split(","))
print ("使用兩個逗號取子串:", sentence.split(",", 2))
python使用“==
”“!=
”操作符比較兩個字符串的內容,如果比較的兩個變量的類型不同,比較的內容也不相同。
# 字符串的比較
str1 = 1
str2 = "1"
if str1 == str2:
print ("相同")
else:
print ("不相同")
if str(str1) == str2:
print ("相同")
else:
print ("不相同")
如果比較字符串中的一部分內容,可以先截取子串,再使用“==
”操作符進行比較,如果要比較字符串的開頭或結尾部分,更方便的方法是使用startwith()
或endwith()
函數。
# 比較字符串的開始和結束處
word = "hello world"
print ("hello" == word[0:5])
print (word.startswith("hello"))
print (word.endswith("ld", 6))
print (word.endswith("ld", 6, 10))
print (word.endswith("ld", 6, len(word)))
字符串反轉是把字符串最後一個字符移到字符串第一個位置按照倒序的方式依次前移。例如:
#函數反轉
def reverse(s):
out = ""
li = list(s)
for i in range(len(li), 0, -1):
out += "".join(li[i-1])
return out
print (reverse("hello"))
上邊的代碼就實現了字符串的反轉。代碼還可以進一步簡化:
#簡化函數反轉
def recerse(s):
li = list(s)
li.reverse()
s = "".join(li)
return s
print (reverse("hello"))
python
的列表是對字符串進行處理的常用方式,靈活使用列表等內置數據結構處理字符串,能夠簡化編程的複雜度。reverse()
函數的主體只需要一行代碼即可。
python
提供了查找字符串的功能。find()
的聲明如下:
find(substring [, start [,end]])
參數substring
表示待查找的字符串,參數start
表示開始搜索的索引位置,參數end
表示結束搜索的索引位置,即在分片[start:end]
中查找。
rfind()
的參數與find()
相同,不同的是rfind()
從字符串的尾部開始查找子串。
# 查找字符串
sentence = "This is a apple."
print (sentence.find("a"))
sentence = "This is a apple."
print (sentence.rfind("a"))
運行結果:
8
10
python
使用函數replace()
實現字符串的替換,該函數可以指定替換的次數,聲明如下:
replace(old, new [, max])
參數old
表示將被替換的字符串,參數new
表示替換old
字符串,參數max
表示使用new
替換old
的次數。
# 字符串的替換
centence = "hello world, hello China"
print (centence.replace("hello", "hi"))
print (centence.replace("hello", "hi", 1))
print (centence.replace("abc", "hi"))
運行結果:
hi world, hi China
hi world, hello China
hello world, hello China
在開發中,經常把日期類型轉換爲字符串類型使用,字符串與日期的在轉換是工作中頻繁遇到的問題。python
提供了time
模塊處理日期和時間。函數strftime()
可以實現從時間到字符串的轉換。strftime()
聲明如下:
strftime(format[, tuple])
參數format
表示格式化日期的特殊字符,例如“%Y-%m-%d
”。參數tuple
表示需要轉換的時間,用元組儲存。元組中的元素分別表示年,月,日,時,分,秒。
字符串到時間的轉換需要進行兩次轉換,需要使用time
模塊和datetime
類。下面這段代碼展示了時間到字符串,字符串到時間的轉換過程。
import time,datetime
# 時間到字符串的轉換
print (time.strftime("%Y-%m-%d %X", time.localtime()))
# 字符串到時間的轉換
t = time.strptime("2008-08-08", "%Y-%m-%d")
y, m, d = t[0:3]
print (datetime.datetime(y, m, d))
函數localtime()
返回當前的時間,strftime()
把當前的時間轉換爲字符串類型。