[Tutor] Python strings example
Peter Otten
__peter__ at web.de
Mon Apr 26 12:22:34 EDT 2021
On 26/04/2021 17:48, Manprit Singh wrote:
> Dear sir,
>
> consider a problem where I have to write a function that can return True if
> the string passed to the function contains at least one digit character and
> one alphabet character, else the function must return False. The way i am
> solving it is given below :
> def str_chk(word_tochk):
> dig = False
> alpha = False
> for ele in word_tochk:
> dig = dig or ele.isdigit()
> alpha = alpha or ele.isalpha()
> return dig and alpha
>
>
> st = "Abhay2"
> ans = str_chk(st)
> print(ans) returns True, which is correct as the string contains an
> alphabet as well as a digit character.
>
> st = "Abhay"
> ans = str_chk(st)
> print(ans) returns False . which is also correct as there is no digit
> character in the string now
>
> Any suggestions, if the solution can be improved .
I would perform the two tests separately. In the worst case you have to
iterate over the string twice, but if you're lucky you only have to scan
a small portion of the string.
def has_digits_and_alphas(s):
return (
any(c.isdigit() for c in s)
and
any(c.isalpha() for c in s)
)
More information about the Tutor
mailing list