Skip to content Skip to sidebar Skip to footer

Python Alphanumeric

Problem: I have to go through text file that has lines of strings and determine about each line if it is alphanumeric or not. If the line is alphanumeric print for example '5345m34

Solution 1:

try this and see if this working -

file = open('file.txt','r')
data = file.readlines()

for i in data:
    stripped_line = i.strip()
    if (stripped_line.isalnum()):
       print (stripped_line, 'is alphanumeric')
    else:
       print (stripped_line, 'not alphanumeric')
file.close()

Solution 2:

EDIT

From your original post you want to treat latin characters (i.e. those with accents) as valid alphanumeric input. In order to do this you should load the original file in unicode and when testing for alphanumeric qualities you should convert the accented letters to normal alphabetic. This will do that:

# -*- coding: utf-8 -*-
import unicodedata
import codecs

file = codecs.open('file.txt','rb', encoding="utf-8")
data = file.readlines()
for i in data:
    i = i.strip()
    converted_data = ''.join((c for c in unicodedata.normalize('NFD', i) if unicodedata.category(c) != 'Mn'))
    if (converted_data.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
file.close()

Post a Comment for "Python Alphanumeric"