Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Here is a straightforward and simple code block. I'd prefer to test every element in the list just to check whether it contains an Alpha Numeric character for additional processing. 

#!/usr/bin/python

words = ["cyberpunk" ,"x10", "hacker" , "x15" , "animegirl" , "x20"]

for x in words:

        print x + " / " +  str(x.isalnum())

This gives the below output:

cyberpunk / True

x10 / True

hacker / True

x15 / True

animegirl / True

x20 / True

If I test is as below:

x = "x10"

print x.isalnum()

x = "this sucks" 

print x.isalnum()

This is the result which I get:

True

False

I just want to know, what is the difference between standalone strings and the list strings

1 Answer

0 votes
by (26.4k points)

You assume isalnum returns True if a string contains both the numbers and letters. What it really does is return True if the string is just letters or numbers. Your last model contains a space, which isn't a letter or number.

You can also build the functionality which you want:

words = ["cyberpunk" ,"x10", "hacker" , "x15" , "animegirl" , "x20", "this sucks"]

def hasdigit(word):

    return any(c for c in word if c.isdigit())

def hasalpha(word):

    return any(c for c in word if c.isalpha())

def hasalnum(word):

    return hasdigit(word) and hasalpha(word)

for word in words:

        print word,'/',hasalnum(word)

Output:

cyberpunk / False

x10 / True

hacker / False

x15 / True

animegirl / False

x20 / True

this sucks / False

Looking for a good python tutorial course? Join the python certification course and get certified.

For more details, do check out the below video tutorial...

Related questions

0 votes
4 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...