一、查找單個字符串
在Python中,我們可以使用內置函數find()來查找單個字符串在指定字符串中的位置。find()的語法如下:
str.find(sub[, start[, end]])
其中,str為指定字符串,sub為要查找的字符串,start和end為可選參數,表示在指定範圍內查找。
如果找到了待查找的字符串,則返回其在字符串中的起始位置,否則返回-1。
以下為一個查找示例:
str = 'hello world'
sub_str = 'world'
position = str.find(sub_str)
if position != -1:
print(f'{sub_str}的位置為{position}')
else:
print(f'沒有找到{sub_str}')
輸出結果為:
world的位置為6
二、查找多個字符串
在查找多個字符串時,我們可以採用正則表達式實現。Python中內置了re(正則表達式)模塊,可以方便地構造和應用正則表達式。
首先,我們需要使用re.compile()函數來編譯正則表達式,並使用search()函數在指定字符串中查找匹配的子串。
以下為一個查找多個字符串的示例:
import re
str = 'hello world'
pattern = re.compile(r'hello|world')
matches = re.findall(pattern, str)
if matches:
print(matches)
else:
print('沒有找到匹配的字符串')
輸出結果為:
['hello', 'world']
三、查找子串出現的次數
在Python中,我們可以使用內置函數count()來查找子串在指定字符串中出現的次數。count()的語法如下:
str.count(sub[, start[, end]])
其中,str為指定字符串,sub為要查找的子串,start和end為可選參數,表示在指定範圍內查找。
以下為一個查找子串出現次數的示例:
str = 'hello world'
sub_str = 'l'
count = str.count(sub_str)
print(f'{sub_str}出現的次數為{count}')
輸出結果為:
l出現的次數為3
四、查找子串並替換
在Python中,我們可以使用內置函數replace()來查找指定的子串並將其替換為指定的字符串。replace()的語法如下:
str.replace(old, new[, count])
其中,str為指定字符串,old為要查找的子串,new為要替換的新字符串,count為可選參數,表示替換的次數。
以下為一個查找子串並替換的示例:
str = 'hello world'
old_str = 'world'
new_str = 'Python'
new_str = str.replace(old_str, new_str)
print(f'替換後的字符串為:{new_str}')
輸出結果為:
替換後的字符串為:hello Python
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/187640.html