Python:从列表中获取所有开头为,开头为和长度为

时间:2018-12-01 10:25:51

标签: 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个字符

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以进行一项列表理解:

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']

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

我找到了解决方法:

# -*- 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)