Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Alphabetical or ASCII?
#3
This logic is wrong:
if x.isalnum():
    if x.isalpha():
        r = "alphabetical"
    if x.isnumeric():
        r = "numeric"
A str can be alphanumeric and not be numeric or alphabetical.
def test(x):
    print("isalnum", x.isalnum())
    print("isalpha", x.isalpha())
    print("isnumeric", x.isnumeric())
    print()


test("a")
test("2")
test("a2")
Output:
isalnum True isalpha True isnumeric False isalnum True isalpha False isnumeric True isalnum True isalpha False isnumeric False
In your code, entering "a2" results in nothing assigned to r. In regular python you would get a name error.
x = "a1"
if x.isalnum():
    if x.isalpha():
        r = "alphabetical"
    if x.isnumeric():
        r = "numeric"
elif x.isspace():
    r = "space-based"
elif x.isascii():
    r = "ASCII text"
else:
    r = "a mystery"

print("x is " + r)
Error:
Traceback (most recent call last): File "...", line 14, in <module> print("x is " + r) NameError: name 'r' is not defined
In the notebook, it just uses the last value assigned to r. Sort of like this :
for x in ("a", "a1", "1", "a1", " ", "a1"):
    if x.isalnum():
        if x.isalpha():
            r = "alphabetical"
        if x.isnumeric():
            r = "numeric"
    elif x.isspace():
        r = "space-based"
    elif x.isascii():
        r = "ASCII text"
    else:
        r = "a mystery"

    print(x, "is", r)
Output:
a is alphabetical a1 is alphabetical 1 is numeric a1 is numeric is space-based a1 is space-based
"a1" is pretty versatile.

I do not know how r could be assigned the input string, Maybe some bizarre convenience feature? If you fix your logic the program will work as expected.
Reply


Messages In This Thread
Alphabetical or ASCII? - by Mark17 - Oct-05-2023, 07:50 PM
RE: Alphabetical or ASCII? - by Larz60+ - Oct-05-2023, 08:41 PM
RE: Alphabetical or ASCII? - by Mark17 - Oct-06-2023, 12:43 PM
RE: Alphabetical or ASCII? - by deanhystad - Oct-05-2023, 08:48 PM
RE: Alphabetical or ASCII? - by Mark17 - Oct-06-2023, 01:27 PM
RE: Alphabetical or ASCII? - by deanhystad - Oct-06-2023, 05:06 PM
RE: Alphabetical or ASCII? - by Mark17 - Oct-06-2023, 06:39 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020