Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

python - 如何在Python中获取角色的位置?(How to get the position of a character in Python?)

如何在python中获取字符串中字符的位置?

  ask by user244470 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two string methods for this, find() and index() .

(有两种字符串方法, find()index() 。)

The difference between the two is what happens when the search string isn't found.

(两者之间的区别是找不到搜索字符串时发生的情况。)

find() returns -1 and index() raises ValueError .

(find()返回-1index()引发ValueError 。)

Using find() (使用find())

>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1

Using index() (使用index())

>>> myString = 'Position of a character'
>>> myString.index('s')
2
>>> myString.index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

From the Python manual (从Python手册)

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end] .

(返回s中找到子字符串sub的最低索引,使得sub完全包含在s[start:end] 。)

Return -1 on failure.

(失败时返回-1 。)

Defaults for start and end and interpretation of negative values is the same as for slices.

(开始结束的默认值以及负值的解释与切片的默认值相同。)

And:

(和:)

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

(与find()类似,但在找不到子字符串时引发ValueError 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...