1樓:酒罈壇兒
defindex
(str1
,char,n
):"""
獲取指定字串中第n個指定字元在字串中的下標:param str1: 指定字串
:param char: 指定字元
:param n: 個數
:return: 下標,如果找不到返回None"""location
=None
count=0
forx
inrange
(len
(str1
)):if
str1[x
]==char
:location=x
count+=1
ifcount==n
:break
return
location
(index
('hallo and hoa'
,'a',2))
2樓:BHznJNs
string
=# 找出第5個a的位置
num=
5replaced
=string
.replace
('a'
,'b'
,num-1
(replaced
.index
('a'
))# >>> 27
3樓:Z先生點記
defindex_a(a
,b):# a為字串,b為索引;ifb
>=0:
init_num=0
#標記出現a的次數
fori,j
inenumerate(a
):ifj==
'a':
init_num+=1
ifinit_num==b
:returni+
1return-1
a_str
='dasdsadsads'
(index_a
(a_str,3
))執行結果如下:
4樓:石頭三顆
import re
s='a good boy, a good girl. a bad man.'
f=re.finditer('a',s)
for i in f:
print(i)
print(i.span())
5樓:Python與演算法社群
def search_n(s, c, n):
size = 0
for i, x in enumerate(sif x == csize += 1
if size == nreturn i
return -1
print(search_n("fdasadfadf", "a", 3))# 結果為7,正確
print(search_n("fdasadfadf", "a", 30))# 結果為-1,正確
python語言中如何判斷乙個字串有多少位?
Python2的str 編碼後的字串,在C中就是char 直接用len 查的長度便是位元組數 Python3的str 可能是UTF 16或UTF 32編碼的字串,在C中是wchar t 通常不要關心它的編碼,而抽象理解為編碼前的字串。所佔位元組數是len 的長度乘以編譯Python所用的編譯器的wc...
python如何統計乙個字串中各字元的數量?
Shreck Ye 其實因為字符集是已知而且連續的,直接按字元編碼對映到乙個記憶體陣列裡面效率要比字典更高。不過既然是Python,變數都是用字典存的,效率似乎就無所謂了,更重要的是怎麼寫更簡單更快。這裡用字典也更方便簡單,參照高讚答案用collections.Counter一行就可以解決更好。 2...
C語言,用陣列定義乙個字串,那這個字串是怎麼儲存在這個陣列中的呢?
the gc 對於scanf的 s的解釋如下 Matches a sequence of non white space characters the nextpointer must be a pointer to the initial element of acharacter array t...