Home > Back-end >  Simplify a funcyion that checks if in string there are numbers or spaces
Simplify a funcyion that checks if in string there are numbers or spaces

Time:01-16

I must create a function that checks if in a string there's a space or a number, and if in this case return false.

I created this code but I feel that is too long, even if it works:

def is_only_string(value):
    if " " in value or "1" in value or "2" in value or "3" in value or "4" in value or "5" in value or "6" in value or "7" in value or "8" in value or "9" in value or "0" in value :
        return False
    else:
        return True

CodePudding user response:

If you want to use a loop you could do:

st = "abdgtss dsg"


def check_for_num(st):
    print(list(st))
    check = False
    for item in list(st):
        if item.isnumeric() or item == " ":
            check = True
            break
    return check


print(check_for_num(st))

CodePudding user response:

You could use

import string
set(value).symmetric_difference(set(string.digits))

string.digits is a string containing every digits character. The difference shows if any of the characters in the value don't appear in the set of digits.

Hope that helps!

CodePudding user response:

If you don't want to use a built-in function like isdigit() (no import needed):

txt = "50800"
x = txt.isdigit()
print(x)
> True

You can use the keywords all or any, which return True respectively if all or at least one of the values in your array is true. small doc here

all([c not in " 1234567890" for c in chars])
  • Related