Python 字符串查找特定字符的位置

Document 对象参考手册 Python3 实例

在 Python 中,我们可以使用 find() 方法来查找字符串中特定字符的位置。find() 方法会返回字符在字符串中第一次出现的索引位置,如果字符不存在,则返回 -1。

实例

# 定义一个字符串
text = "Hello, welcome to the world of Python."

# 查找字符 'w' 的位置
position = text.find('w')

# 输出结果
print("The position of 'w' is:", position)

代码解析:

  • text = "Hello, welcome to the world of Python.":定义一个字符串 text
  • position = text.find('w'):使用 find() 方法查找字符 'w' 在字符串 text 中的位置,并将结果存储在变量 position 中。
  • print("The position of 'w' is:", position):输出字符 'w' 的位置。

输出结果:

The position of 'w' is: 7

在这个例子中,字符 'w' 在字符串中的索引位置是 7。

Document 对象参考手册 Python3 实例