Test a single-line file for punctuation and newline I have written the following program to read from a file (entire input in single line) and check for:


ASCII punctuation characters
a final newline




import re
file_name=input("Please enter the file name ")
with open(file_name, 'r') as fp:
    context=fp.read()
    regex = re.compile('[@_!#$%^&amp;*()&lt;&gt;?/\|} {~]')
    if regex.search(context) is None: 
        print("No special character found")
    else: 
        print("Special character found") 
    for x in range(0,len(context)-1):
        if (context[x].isspace())==True:
            print("spaces found in the file at ", x)
            break
        else:
            pass
        #print("No space found")
    for x in range(0, len(context)-1):
        if context[x]=='\n' or context[x]=='"':
            print("Yes new line is there at", x)
            break
        else:
            pass
        #print("No new line ")
\| is not a proper escape sequence.  To include the backslash in the string, it should be escaped using two backslashes, or you should use a “raw” string for the regular expression, so backslashes do not need to be escaped.

for x in range(0, len(context) - 1): does not check the last character of the string, since range(start, end) already does not include end.

if (context[x].isspace())==True: does not need the parentheses around context[x].isspace(), nor does it need the == True.

You can use enumerate() to loop over the contents of an iterable and get the index at the same time.  Also, a for ... else block can be used to detect if nothing was found.  With Python 3.6 or later, f-strings can be used to embed variables directly in strings.

for idx, ch in enumerate(context):
    if ch.isspace():
        print(f"spaces found in the file at {idx}")
        break
else:
    print("no space found")


It is strange to find a quotation mark, and declare that a new line has been found.  Are you sure you’ve got your logic correct?

PEP8 Guidelines:


spaces around all operators, like =, ==, -
use a space after each comma in argument lists
blank line after imports
longer, descriptive variable names (x is too short and not descriptive)