新聞中心
在Python中,我們可以使用內置的字符串方法來查找子字符串,以下是一些常用的字符串查找方法:

1、str.find(sub[, start[, end]])
2、str.index(sub[, start[, end]])
3、str.count(sub[, start[, end]])
4、str.startswith(prefix[, start[, end]])
5、str.endswith(suffix[, start[, end]])
6、str.lower()
7、str.upper()
8、str.replace(old, new[, count])
下面是這些方法的詳細解釋和示例代碼:
1、str.find(sub[, start[, end]])
此方法返回子字符串在字符串中首次出現(xiàn)的最小索引,如果未找到則返回1,可選參數(shù)start和end用于指定搜索的起始和結束位置。
“`python
text = "Hello, world!"
print(text.find("world")) # 輸出: 7
print(text.find("world", 8)) # 輸出: 1
“`
2、str.index(sub[, start[, end]])
此方法與str.find()類似,但如果未找到子字符串,則會引發(fā)ValueError異常。
“`python
text = "Hello, world!"
print(text.index("world")) # 輸出: 7
print(text.index("world", 8)) # 拋出異常: ValueError: substring not found
“`
3、str.count(sub[, start[, end]])
此方法返回子字符串在字符串中出現(xiàn)的次數(shù),可選參數(shù)start和end用于指定搜索的起始和結束位置。
“`python
text = "Hello, world! The world is beautiful."
print(text.count("world")) # 輸出: 2
“`
4、str.startswith(prefix[, start[, end]])
此方法檢查字符串是否以指定的前綴開頭,可選參數(shù)start和end用于指定搜索的起始和結束位置。
“`python
text = "Hello, world!"
print(text.startswith("Hello")) # 輸出: True
print(text.startswith("world", 7)) # 輸出: False
“`
5、str.endswith(suffix[, start[, end]])
此方法檢查字符串是否以指定的后綴結尾,可選參數(shù)start和end用于指定搜索的起始和結束位置。
“`python
text = "Hello, world!"
print(text.endswith("!")) # 輸出: True
print(text.endswith("world", 0, 5)) # 輸出: False
“`
6、str.lower()
此方法返回字符串的小寫版本。
“`python
text = "Hello, World!"
print(text.lower()) # 輸出: "hello, world!"
“`
7、str.upper()
此方法返回字符串的大寫版本。
“`python
text = "Hello, World!"
print(text.upper()) # 輸出: "HELLO, WORLD!"
“`
8、str.replace(old, new[, count])
此方法返回一個新的字符串,其中所有出現(xiàn)的舊子字符串都被新子字符串替換,可選參數(shù)count用于指定最大替換次數(shù)。
“`python
text = "Hello, world!"
print(text.replace("world", "Earth")) # 輸出: "Hello, Earth!"
“`
文章標題:python如何字符串查找
鏈接URL:http://www.dlmjj.cn/article/cojjegc.html


咨詢
建站咨詢
