跳到主要内容

Python 字符串 startswith() 方法

startswith() 方法在字符串以指定的前缀(字符串)开头时返回 True。如果不是,则返回 False

示例

message = 'Python is fun'

# 检查 message 是否以 Python 开头
print(message.startswith('Python'))

# 输出: True

String startswith() 语法

startswith() 的语法是:

str.startswith(prefix[, start[, end]])

startswith() 参数

startswith() 方法最多可以接受三个参数:

  • prefix - 要检查的字符串或字符串元组
  • start(可选)- 字符串中开始检查 prefix 的位置。
  • end(可选)- 字符串中结束检查 prefix 的位置。

startswith() 返回值

startswith() 方法返回布尔值。

  • 如果字符串以指定的前缀开头,返回 True。
  • 如果字符串不以指定的前缀开头,返回 False。

示例 1:没有 start 和 end 参数的 startswith()

text = "Python is easy to learn."

result = text.startswith('is easy')
# 返回 False
print(result)

result = text.startswith('Python is ')
# 返回 True
print(result)

result = text.startswith('Python is easy to learn.')
# 返回 True
print(result)

输出

False
True
True

示例 2:带有 start 和 end 参数的 startswith()

text = "Python programming is easy."

# start 参数: 7
# 搜索 'programming is easy.' 字符串
result = text.startswith('programming is', 7)
print(result)

# start: 7, end: 18
# 搜索 'programming' 字符串
result = text.startswith('programming is', 7, 18)
print(result)

result = text.startswith('program', 7, 18)
print(result)

输出

True
False
True

向 startswith() 传递元组

在 Python 中,可以向 startswith() 方法传递一个前缀元组。

如果字符串以元组中的任何一项开头,startswith() 返回 True。如果不是,则返回 False。

示例 3:带有元组前缀的 startswith()

text = "programming is easy"
result = text.startswith(('python', 'programming'))

# 输出 True
print(result)

result = text.startswith(('is', 'easy', 'java'))

# 输出 False
print(result)

# 带有 start 和 end 参数
# 检查 'is easy' 字符串
result = text.startswith(('programming', 'easy'), 12, 19)

# 输出 False
print(result)

输出

True
False
False

如果你需要检查字符串是否以指定的后缀结尾,可以使用 Python 中的 endswith() 方法