Python 查詢字元在字串中的位置例項

2022-09-29 22:30:34 字數 742 閱讀 9626

如下所示:

str_1='wo shi yi zhi da da niu '

char_1='i'

npos=str_1.index(char_1)

print(npos)

執行結果:7

*****===是使用find===njxgh*****==

str_1='wo shi yi zhi da da niu '

char_1='i'

npos=str_1.find(char_1)

print(npos)

結果:5

*****===如何查詢所有『i'在字串中位置呢?**********=

#開掛模式

str_1='wo shi yi zhi da da niu '

char_1=str(input('please input the char you want:'))

count=0

str_list=list(str_1)

for each_char in str_list:

count+=1

if ea程式設計客棧ch_char==char_1:

print(each_char,count-1)

執行程式設計客棧結果

please input the char you want:i

i 0i 1

i 2i 3

本文標題: python 查詢字元在字串中的位置例項

本文位址:

python在字串中查詢字元

兩類函式 find rfind index rindex 找到了都返回下標.find找不到返回 1,index找不到丟擲valueerror.帶r的表示從右向左找.都可以使用第二個引數表示從哪個下標開始找.a abcdab a.find a out 3 0 a.rfind a out 4 4a.rf...

查詢字串中字元位址

這個函式引數中的陣列array是以 0結束的字串,要求在字串array中查詢出第乙個與引數search給出的字元相同的字元。如果找到,通過第三個引數 pa 返回array字串中首先碰到的search字元的位址。如果沒找到,則pa為null。include include include includ...

查詢字串

在乙個主串中查詢相應的子串,如 abcdwoshidef 中查詢 woshi 方法 該實現的方法是最簡單的模式匹配方法,時間複雜度較高 include iostream using namespace std int searchstring const char str1,const char s...