要查找一个单词在字符串中的位置,可以使用字符串的 find()
方法或 index()
方法。这两种方法都可以用来查找子字符串在原始字符串中的位置索引。
- 使用
find()
方法:
s = "hello world"
word = "world"
position = s.find(word)
if position != -1:
print("单词 '{}' 在字符串中的位置是 {}".format(word, position))
else:
print("单词 '{}' 未在字符串中找到".format(word))
- 使用
index()
方法:
s = "hello world"
word = "world"
try:
position = s.index(word)
print("单词 '{}' 在字符串中的位置是 {}".format(word, position))
except ValueError:
print("单词 '{}' 未在字符串中找到".format(word))
这两种方法的区别在于,find()
方法在字符串中找不到子字符串时返回 -1
,而 index()
方法在找不到时会抛出 ValueError
异常。因此,如果确定要查找的单词一定存在于字符串中,可以使用 index()
方法,否则建议使用 find()
方法,以避免异常。