我如何判断字母在字符串中的索引?(在Python、JS、Ruby、PHP等中)

2024-05-01 15:42:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
print alphabet[0]
# prints a
print alphabet[25]
#prints z

以此类推,但我如何找出相反的结果,即:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
's' = alphabet[?]
""" The question mark represents that I want to know 
what index the letter is in the string."""

Tags: thetoindexthatprintswhatmarkquestion
3条回答

在Python中,要获取字符串中某个字符的位置,应该是:

alphabet.index('s')

在javascript中,可以使用alphabet.indexOf('a')。你知道吗

在python中,可以使用find方法:

>>> alphabet = 'abcdefghijklmnopqrstuvwxyz' 
>>> alphabet.find('a')
0
>>> alphabet.find('b')
1
>>> alphabet.find('c')
>>> alphabet.find('z')
25

Edit to add:正如Warren指出的那样,您也可以使用index,区别在于find将返回-1作为未找到的位置,而index将在未找到时引发ValueError。你知道吗

在javascript中,使用indexOf

> "abc".indexOf("b")
1

相关问题 更多 >