Print the string, if string in the line ends with specific characters
<p>How do I print every string that ends on 'je' in a line</p>

<p>For example : </p>

<pre><code>for line in sys.stdin:
    for string in line:
        if string ends with 'je':
            print string
</code></pre>

<p>And only if the string ends with '....je' , so no 'je' included. And if the string ends with '....je?' or '....je.' remove '? , . ' . Then it should print the string. Help would be appreciated.</p>

<p>There are two problems in your code. <code>for string in line:</code> will go through every single character, not through every word. By the way, you should not name your variable <code>string</code>. <code>for word in line.split():</code> will do what you expect.</p>

<p>Also, <code>if string ends with 'je':</code> should be <code>if word.endswith('je'):</code>. If you don't want to match the exact word "je", you can change that to <code>if word.endswith('je') and word != "je":</code>.</p>

<p>Final code, including the removal of <code>!</code> and <code>?</code>:</p>

<pre><code>f = open("a.txt", "r")

for line in f:
    for word in line.split():
        word = word.rstrip("!?")
        if word.endswith('je') and word != "je":
            print(word)
</code></pre>

<p>Note that if a word ends with several <code>?</code> or <code>!</code>, they will all get removed.</p>

python string file character line