How to display all words that contain these characters?

If you don't want to have 2 problems:

for word in file('myfile.txt').read().split():
    if 'x' in word and 'z' in word:
        print word

Assuming you have the entire file as one large string in memory, and that the definition of a word is "a contiguous sequence of letters", then you could do something like this:

import re
for word in re.findall(r"\w+", mystring):
    if 'x' in word and 'z' in word:
        print word

>>> import re
>>> pattern = re.compile('\b(\w*z\w*x\w*|\w*x\w*z\w*)\b')
>>> document = '''Here is some data that needs
... to be searched for words that contain both z
... and x.  Blah xz zx blah jal akle asdke asdxskz
... zlkxlk blah bleh foo bar'''
>>> print pattern.findall(document)
['xz', 'zx', 'asdxskz', 'zlkxlk']

Tags:

Python