[英]Check if a string starts with the a specific word, if True then print word - PYTHON
我有一个字符串列表,我想迭代每个字符串并检查字符串是否以“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
它完全按照您的预期执行;)。
顺便说一下,您应该只对类使用大写变量名 。
你可能不应该考虑其他一些方法,但为了它的乐趣,我把它们包括在内: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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.