猿问

在列表中搜索字符串python中的值

尝试搜索此列表


a = ['1 is the population', '1 isnt the population', '2 is the population']

如果可以实现,我想做的是在列表中搜索值1。如果值存在,则打印字符串。


如果数字存在,我想要获得的输出是整个字符串。如果值1存在,我想获得的输出将打印字符串。IE


1 is the population 

2 isnt the population 

上面是我想要的输出,但是我不知道如何得到它。是否可以在列表及其字符串中搜索值1,如果出现值1,则输出字符串


叮当猫咪
浏览 163回答 3
3回答

慕标5832272

for i in a:    if "1" in i:        print(i)

泛舟湖上清波郎朗

您应该regex在这里使用:in 对于此类字符串也将返回True。>>> '1' in '21 is the population'True代码:>>> a = ['1 is the population', '1 isnt the population', '2 is the population']>>> import re>>> for item in a:...     if re.search(r'\b1\b',item):...         print item...         1 is the population1 isnt the population

蝴蝶刀刀

def f(x):    for i in a:        if i.strip().startswith(str(x)):            print i        else:            print '%s isnt the population' % (x)f(1) # or f("1")这比进行"1" in x样式检查更准确/更严格,特别是如果您的句子'1'在字符串中的其他任何地方都具有非语义字符时。例如,如果您有一个字符串怎么办"2 is the 1st in the population"您在输入数组中有两个语义上矛盾的值:a = ['1 is the population', '1 isnt the population', ... ]这是故意的吗?
随时随地看视频慕课网APP

相关分类

Python
我要回答