![]() |
Find if chain of characters or number - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Find if chain of characters or number (/thread-36358.html) |
Find if chain of characters or number - Frankduc - Feb-10-2022 Hello, Try to determine if its a chain of characters or numbers. mot = input("input something: ") for num in mot: if num not in "0123456789": print("its ccharacters") else: print("its number") The problem it is checking every characters one by one and i just want to tell for the whole word.Dont use isnumber or digit gadget. TY RE: Find if chain of characters or number - menator01 - Feb-10-2022 Might try this. If the string has numbers and letters ir will return as a string. while True: prompt = input('input: ') if prompt == 'q': break try: if int(prompt): print('numbers') except ValueError: print('letters')
RE: Find if chain of characters or number - deanhystad - Feb-10-2022 You can use "isnumeric()" print('123'.isnumeric(), 'abc'.isnumeric(), '1.23'.isnumeric()) You can use a regular expression.import re is_int = re.compile(r'^-?\d*$') print(is_int.match('123') is not None) print(is_int.match('abc') is not None) print(is_int.match('1.23') is not None) print(is_int.match('-123') is not None) As menator01 recommends, conversion (you probably want the numeric value anyway) and catching the exception is likely the best solution. Use float() instead of int() if you want to allow decimals.
RE: Find if chain of characters or number - menator01 - Feb-10-2022 Updated to include floats while True: prompt = input('input: ') if prompt == 'q': break try: int(prompt) print('number') except ValueError: try: float(prompt) print('float') except ValueError: print('letters')
RE: Find if chain of characters or number - Frankduc - Feb-11-2022 Hello guys. Sorry for the late reply, i had courses yesterday since i started in AI. The book was asking for brute force approach. You cannot use try, except, import or isnumeric. It is tempting i admit to use gadget but forbidden. I came up with that solution in my bed at one am. Sorry its in french. mot = input("Une chaîne de charactères svp!: ") count = 0 for num in mot: if num in "0123456789": count += 1 if count == len(mot): print("Il s'agit d'un nombre entier de", count, "chiffres") else: print("Il s'agit d'une chaîne de caractères.") Thanks guys for the help. I will take in note some of your suggestion.
|