Katrina
Katrina

Reputation: 33

How do I determine if all the characters in a string is alphanumeric without using isalnum()?

I want to determine if all the characters in a given string (say z) are alphanumeric (numbers and letters only).

The function should return True if the string is alphanumeric and False if not. I additionally want to avoid using conditional branching, relational, or Boolean operators, or any built in functions except type casting functions.

For any iteration, use a while loop with condition: True. Use try and except blocks.

what I have so far:

def is_alnum(z):
    i = 0
    y = 0
    while True:
        try:
            try:
                y = int(z[i])
            except(ValueError):
                   ### don't know what to insert
        except(IndexError):
            return True
        i += 1

Upvotes: 0

Views: 873

Answers (2)

sahinakkaya
sahinakkaya

Reputation: 6056

Here is a solution with just using the builtin function int:

def is_alnum(z):
    try:
        int(z, base=36)
    except ValueError:
        return False
    else:
        return True

>>> is_alnum('abc123')
True
>>> is_alnum('abc-123')
False

From the documentation:

base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.

Upvotes: 1

JarroVGIT
JarroVGIT

Reputation: 5324

How about this:

def is_alnum(z):
    i=1
    abcnum = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 
    'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
    'u', 'v', 'w', 'x', 'y', 'z'] + [str(i) for i in range(10)]    
    while True:
        try:
            chr = z[i-1].lower()
        except IndexError:
            return True
        try:
            idx = abcnum.index(chr)
        except ValueError as e:
            return False 
        i += 1

This will result in:

print(is_alnum("Yeah!!")) -> False (because of !!)

print(is_alnum("thisistrue")) -> True

Upvotes: 0

Related Questions