簡體   English   中英

Python在索引后找到第一個出現的字符

[英]Python find first occurrence of character after index

我試圖獲取指定索引的字符串中出現的第一個字符的索引。 例如:

string = 'This + is + a + string'

# The 'i' in 'is' is at the 7th index, find the next occurrence of '+'
string.find_after_index(7, '+')

# Return 10, the index of the next '+' character
>>> 10

Python是如此可預測:

>>> string = 'This + is + a + string'
>>> string.find('+',7)
10

結帳help(str.find)

find(...)
    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.

也適用於str.index除了在找不到子字符串時會raise ValueError而不是-1

您可以使用:

start_index = 7
next_index = string.index('+', start_index)
string.find('+', 7)

閱讀文檔

In [1]: str.index?
Docstring:
S.index(sub[, start[, end]]) -> int

Like S.find() but raise ValueError when the substring is not found.
Type:      method_descriptor

In [2]: string = 'This + is + a + string'

In [3]: string.index('+', 7)
Out[3]: 10
for i in range(index, len(string)):
    if string[i] == char:
         print(i)

上面的代碼將從你提供index的索引循環到字符串len(string)的長度。 然后,如果字符串的索引等於您要查找的字符char ,那么它將打印索引。

你可以將它放在一個函數中並傳入,字符串,索引和字符,然后返回i。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM