Python:使用startswith、endswith和lengh从列表中获取所有发生的事件

2024-09-28 23:22:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的词表中搜索一些条件。你知道吗

这是我代码的一部分:

# -*- coding: utf-8 -*-

with open(r"C:\Users\Valentin\Desktop\list.txt") as f:
    content = f.readlines()
content = [x.strip() for x in content] 

all_words = ','.join(content)
end = all_words.endswith('e')

我的清单如下:

'cresson', 'crête', 'Créteil', 'crétin', 'creuse', 'creusé', 'creuser',...

我想设置这些条件:

  • 以字母“C”开头
  • 以字母“E”结尾
  • 长度:9个字符

我怎么能做到?你知道吗


Tags: 代码with字母opencontentall条件users
3条回答

我找到了解决办法:

# -*- coding: utf-8 -*-

with open(r"C:\Users\Valentin\Desktop\list.txt") as f:
    content = f.readlines()

# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
#print(content) 

result = [i for i in content if i.startswith('c')]
result2 = [i for i in result if i.endswith('e')]
result3 = [i for i in result2 if len(i)==9]
print(result3)

你可以做一个列表:

content = ['cresson', 'crête', 'Créteil', 'crétin', 'creuse', 'creusé', 'creuser']

result = [x for x in content if len(x) == 9 and x.startswith() == 'c' and x.endswith() == 'e']

假设不区分大小写,并且您可以访问f字符串(Python3.6):

[s for s in content if len(s) == 9 and f'{s[0]}{s[-1]}'.lower() == 'ce']

相关问题 更多 >