python字符串-查找(find)


find方法是一個基本的字符串查找的操作。

  • find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,如果包含子字符串返回開始的索引值,否則返回-1。

語法:

S.find(sub[, start[, end]]) -> int

參數

  • str:要查找的字符串。
  • start:可選參數,開始索引,默認為0。
  • end:可選參數,結束索引,默認為字符串長度。

返回值

  • 如果包含子字符串返回開始的索引值,否則返回-1。

示例

str = '我愛我的爸媽'
print('返回子字符串開始的偏移量:', str.find('我的'))
print('指定開始索引:', str.find('我的', 3))
print('指定結束索引:', str.find('我的', 0, 2))
print('沒有找到的情況下返回-1:', str.find('姐姐'))
返回子字符串開始的偏移量: 2
指定開始索引: -1
指定結束索引: -1
沒有找到的情況下返回-1: -1

help(str.find)

find(...) method of builtins.str instance
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM