I am a bit in trouble in a way to select a bunch of letters in a for loop that select words in a list which do not contain these letters;
Bellow the code I am trying to use, when I assign string with just one char, it print all words in words.txt that do not contain that char, but if I assign string with more than one char it consider the whole string, even using a ( for letter in string )
def avoids_2():
string = 'abc'
fin = open('words.txt')
for letter in string:
for line in fin:
if letter not in line:
word = line.strip()
print(word)
Please, does anyone knows how to solve?
Issue with your code is that you are searching for only one character at a time ie if your letter is c
it will look for only c
and print strings with a
or b
too in the internal loop. So you can change it like this
fin = open('words.txt')
test_string = 'abc'
for line in fin:
flag = False
for letter in test_string:
if letter in line:
flag = True
break
if not flag:
print(line.strip())
You can also use regex here
import re
fin = open('words.txt')
for line in fin:
if re.match(r'a|b|c', line):
continue
print(line.strip())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.