In your second function you apply any to a single element and not to the whole list. Thus, you get a single bool element if character i is alphanumeric.
In the second case you cannot really use any as you work with single elements. Instead you could write:
for i in s:
if i.isalnum():
print(True)
break
Which will be more similar to your first case.
Answer from JohanL on Stack OverflowVideos
In your second function you apply any to a single element and not to the whole list. Thus, you get a single bool element if character i is alphanumeric.
In the second case you cannot really use any as you work with single elements. Instead you could write:
for i in s:
if i.isalnum():
print(True)
break
Which will be more similar to your first case.
any() expects an iterable. This would be sufficient:
isalnum = False
for i in s:
if i.isalnum():
isalnum = True
break
print(isalnum)
You seem to think isalnum returns True if a string contains both letters and numbers. What it actually does is return True if the string is only letters or numbers. Your last example contains a space, which is not a letter or number.
You can build up the functionality 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
Your string that fails contains a space character. None of the entries in the list contains a space.
» pip install python-dotenv