我有一个字符串列表,我想遍历每个字符串并检查字符串是否以单词“Base”开头,如果是,我想打印它。
列表
SideMembers = ["Unweighted Base","Base: All GB Adults","A savings account","None of these"]
这是我的尝试
for word in SideMember:
if word[0] == "B":
print word
这可行,但如您所见,它不是很强大,我不完全知道如何比较整个单词。
for word in SideMember:
if "Base" in word:
print word:
这实际上不起作用,因为它打印 SideMembers[0]
和 SideMembers[1]
因为它们都包含“Base”。
希望得到一些帮助...
谢谢
最佳答案
您可以使用str.startswith()
:
for word in SideMember:
if word.startswith('Base'):
print word
它的表现完全符合您的预期;)。
顺便说一句,你should only use capitalised variable names for classes .
您可能不应该考虑其他一些方法,但为了好玩,我将它们包括在内:p
import re
for word in sidemembers:
if re.search(r'^Base', word) is not None:
print word
for word in sidemembers:
if word[:4] == 'Base':
print word
关于python - 检查字符串是否以特定单词开头,如果为 True,则打印单词 - PYTHON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696944/