문자열 입력이 숫자인지 확인하려면 어떻게 해야 합니까?
사용자의 문자열 입력이 숫자인지 확인하려면 어떻게 해야 합니까(예:-1
,0
,1
등등?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
다음 이후로 위의 작업이 작동하지 않습니다.input
항상 문자열을 반환합니다.
단순히 int로 변환한 다음 작동하지 않으면 구제해 보십시오.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
음의 값에는 효과가 없지만 양의 값에는 효과가 있습니다.
사용하다isdigit()
if userinput.isdigit():
#do stuff
메소드가 작업을 수행합니다.
>>>a = '123'
>>>a.isnumeric()
True
그러나 기억해:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric()
아온다를 합니다.True
문자열의 모든 문자가 숫자이고 하나 이상의 문자가 있는 경우.
그래서 음수는 허용되지 않습니다.
Python 3의 경우 다음이 작동합니다.
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
편집됨: 아래 코드를 사용하여 숫자인지 음수인지 확인할 수도 있습니다.
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
특정 요구 사항에 맞게 형식을 변경할 수도 있습니다.저는 이 게시물을 너무 늦게 봅니다.하지만 이것이 답을 찾고 있는 다른 사람들에게 도움이 되기를 바랍니다 :) . 주어진 코드에서 잘못된 것이 있으면 저에게 알려주세요.
특히 int 또는 float이 필요한 경우 "is not int" 또는 "is not float"을 시도할 수 있습니다.
user_input = ''
while user_input is not int:
try:
user_input = int(input('Enter a number: '))
break
except ValueError:
print('Please enter a valid number: ')
print('You entered {}'.format(user_input))
만약 당신이 ints로만 작업한다면, 내가 본 가장 우아한 해결책은 ".isdigit()" 방법입니다.
a = ''
while a.isdigit() == False:
a = input('Enter a number: ')
print('You entered {}'.format(a))
입력이 양의 정수이고 특정 범위에 있는지 확인하는 데 문제가 없습니다.
def checkIntValue():
'''Works fine for check if an **input** is
a positive Integer AND in a specific range'''
maxValue = 20
while True:
try:
intTarget = int(input('Your number ?'))
except ValueError:
continue
else:
if intTarget < 1 or intTarget > maxValue:
continue
else:
return (intTarget)
음의 숫자에 대해 @karthik27을 추천합니다.
import re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
그런 다음 그 정규 표현으로 원하는 것은 무엇이든 하세요, match(), find all()
자연: [0, 1, 2...∞]
파이썬 2
it_is = unicode(user_input).isnumeric()
파이썬 3
it_is = str(user_input).isnumeric()
정수: [-숫자, ..., -2, -1, 0, 1, 2, ∞]
try:
int(user_input)
it_is = True
except ValueError:
it_is = False
float: [-dll, ..., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]
try:
float(user_input)
it_is = True
except ValueError:
it_is = False
가장 우아한 해결책은 이미 제안된 것입니다.
a = 123
bool_a = a.isnumeric()
유감스럽게도, 음의 정수나 a의 일반적인 부동 소수 값에 대해서는 작동하지 않습니다.만약 당신의 요점이 'a'가 정수를 넘어선 일반적인 숫자인지 확인하는 것이라면, 저는 다음과 같은 것을 제안하고 싶습니다. 이것은 모든 종류의 부동소수와 정수에 적용됩니다.테스트는 다음과 같습니다.
def isanumber(a):
try:
float(repr(a))
bool_a = True
except:
bool_a = False
return bool_a
a = 1 # Integer
isanumber(a)
>>> True
a = -2.5982347892 # General float
isanumber(a)
>>> True
a = '1' # Actually a string
isanumber(a)
>>> False
이 솔루션은 정수만 사용하고 정수만 사용할 수 있습니다.
def is_number(s):
while s.isdigit() == False:
s = raw_input("Enter only numbers: ")
return int(s)
# Your program starts here
user_input = is_number(raw_input("Enter a number: "))
이것은 분수를 포함한 모든 숫자에서 작동합니다.
import fractions
def isnumber(s):
try:
float(s)
return True
except ValueError:
try:
Fraction(s)
return True
except ValueError:
return False
문자열에 isdigit() 메서드를 사용할 수 있습니다.이 경우 입력은 항상 문자열입니다.
user_input = input("Enter something:")
if user_input.isdigit():
print("Is a number")
else:
print("Not a number")
입력을 숫자로 나누는 것이 어떻습니까?이 방법은 모든 것에 적용됩니다.부정적인 것, 부유한 것, 그리고 부정적인 것.공백과 0도 있습니다.
numList = [499, -486, 0.1255468, -0.21554, 'a', "this", "long string here", "455 street area", 0, ""]
for item in numList:
try:
print (item / 2) #You can divide by any number really, except zero
except:
print "Not A Number: " + item
결과:
249
-243
0.0627734
-0.10777
Not A Number: a
Not A Number: this
Not A Number: long string here
Not A Number: 455 street area
0
Not A Number:
이것이 꽤 늦은 것은 알지만 이것을 알아내기 위해 6시간을 소비해야 했던 다른 사람들을 돕기 위한 것입니다.(내가 한 짓이 그거야)
이것은 완벽하게 작동합니다: (입력에 문자가 있는지 확인/입력이 정수인지 부동인지 확인)
a=(raw_input("Amount:"))
try:
int(a)
except ValueError:
try:
float(a)
except ValueError:
print "This is not a number"
a=0
if a==0:
a=0
else:
print a
#Do stuff
INT와 RANGE의 입력을 확인하는 간단한 기능이 있습니다.여기서 입력이 1-100 사이의 정수이면 'True'를 반환하고, 그렇지 않으면 'False'를 반환합니다.
def validate(userInput):
try:
val = int(userInput)
if val > 0 and val < 101:
valid = True
else:
valid = False
except Exception:
valid = False
return valid
이 부유물을 , 이 부액을합격면려키시평동고가를 받아들이고 싶다면.NaN
입력으로 사용하지만 다른 문자열은 사용하지 않습니다.'abc'
다음을 수행할 수 있습니다.
def isnumber(x):
import numpy
try:
return type(numpy.float(x)) == float
except ValueError:
return False
저는 제가 공유할 것이라고 생각했던 다른 접근법을 사용해 왔습니다.유효한 범위를 만드는 것부터 시작합니다.
valid = [str(i) for i in range(-10,11)] # ["-10","-9...."10"]
이제 번호를 묻고 목록에 없는 경우 다음을 계속 묻습니다.
p = input("Enter a number: ")
while p not in valid:
p = input("Not valid. Try to enter a number again: ")
마지막으로 int로 변환합니다(목록에 문자열로 정수만 포함되어 있기 때문에 작동합니다).
p = int(p)
while True:
b1=input('Type a number:')
try:
a1=int(b1)
except ValueError:
print ('"%(a1)s" is not a number. Try again.' %{'a1':b1})
else:
print ('You typed "{}".'.format(a1))
break
이렇게 하면 입력이 정수인지 여부를 확인하는 루프가 발생하며, 결과는 다음과 같습니다.
>>> %Run 1.1.py
Type a number:d
"d" is not a number. Try again.
Type a number:
>>> %Run 1.1.py
Type a number:4
You typed 4.
>>>
또한 오늘 아침 사용자가 정수에 대한 특정 요청에 대해 정수가 아닌 응답을 입력할 수 있는 문제가 발생했습니다.
이것이 제가 원하는 답을 강요하는 데 효과적인 해결책이었습니다.
player_number = 0
while player_number != 1 and player_number !=2:
player_number = raw_input("Are you Player 1 or 2? ")
try:
player_number = int(player_number)
except ValueError:
print "Please enter '1' or '2'..."
시도에 도달하기도 전에 예외가 발생할 수 있습니다. 사용할 때의 문장
player_number = int(raw_input("Are you Player 1 or 2? ")
사용자는 "J" 또는 기타 정수가 아닌 문자를 입력했습니다.원시 입력으로 가져가서 해당 원시 입력을 정수로 변환할 수 있는지 확인한 다음 나중에 변환하는 것이 가장 좋습니다.
이렇게 하면 됩니다.
print(user_input.isnumeric())
문자열에 숫자만 있고 길이가 1 이상인지 확인합니다.그러나 음수가 포함된 문자열이 있는 숫자를 시도하면 숫자가 반환됩니다.False
.
자, 이것은 음수와 양수 모두에 효과가 있는 솔루션입니다.
try:
user_input = int(user_input)
except ValueError:
process_non_numeric_user_input() # user_input is not a numeric string!
else:
process_user_input()
지금까지 부정적인 것과 소수를 다루는 답은 단 두 가지인 것 같습니다. 답변과 정규식을 제외하고는?)얼마 전 어딘가에서 완전한 정규식이 아닌 각 문자에 대한 명시적인 직접 검사를 사용하는 세 번째 답변을 찾았습니다(검색을 시도했지만 성공하지 못했습니다.
여전히 시도/예외 방법보다 훨씬 느린 것처럼 보이지만, 이러한 방법을 사용하지 않으려면 일부 사용 사례는 특히 일부 숫자가 짧거나 음수가 아닌 경우에 많이 사용할 때 정규식에 비해 더 나을 수 있습니다.
>>> from timeit import timeit
Windows의 Python 3.10에서는 다음과 같은 결과가 나타납니다.
각 문자를 명시적으로 확인합니다.
>>> print(timeit('text="1234"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
0.5673831000458449
>>> print(timeit('text="-4089175.25"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.0832774000009522
>>> print(timeit('text="-97271851234.28975232364"; z=text[0]; (z.isdigit() or z == "-" or z == ".") and all(character.isdigit() or character == "." for character in text[1:])'))
1.9836419000057504
시도보다 훨씬 느림/단, 다음을 제외하고는:
>>> def exception_try(string):
... try:
... return type(float(string)) == int
... except:
... return false
>>> print(timeit('text="1234"; exception_try(text)', "from __main__ import exception_try"))
0.22721579996868968
>>> print(timeit('text="-4089175.25"; exception_try(text)', "from __main__ import exception_try"))
0.2409859000472352
>>> print(timeit('text="-97271851234.28975232364"; exception_try(text)', "from __main__ import exception_try"))
0.45190039998851717
하지만 정규식보다 꽤 빠르죠, 극도로 긴 끈을 가지고 있지 않다면요?
>>> print(timeit('import re'))
0.08660140004940331
(이미 사용 중인 경우)...다음과 같은 경우:
>>> print(timeit('text="1234"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.3882658999646083
>>> print(timeit('text="-4089175.25"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4007637000177056
>>> print(timeit('text="-97271851234.28975232364"; import re; num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"); re.match(num_format,text)'))
1.4191589000402018
가장 단순한 십진법에 가까운 것은 없지만, 물론 부정적인 것들을 잡을 수는 없습니다.
>>> print(timeit('text="1234"; text.isdecimal()'))
0.04747540003154427
필요에 따라 옵션을 선택할 수 있는 것이 항상 좋습니까?
일부 Python 라이브러리는 프로그래머-사용자가 제공하는 값이 숫자인지 확인하기 위해 어설션을 사용합니다.
때로는 '야생에서 온' 예를 보는 것이 좋습니다.사용.assert
/isinstance
:
def check_port(port):
assert isinstance(port, int), 'PORT is not a number'
assert port >= 0, 'PORT < 0 ({0})'.format(port)
저는 한 줄로 간단한 것을 하지 않는 것은 피톤적이지 않다고 생각합니다.
다음이 없는 경우try..except
정규식 일치 사용:
코드:
import re
if re.match('[-+]?\d+$', the_str):
# Is integer
테스트:
>>> import re
>>> def test(s): return bool(re.match('[-+]?\d+$', s))
>>> test('0')
True
>>> test('1')
True
>>> test('-1')
True
>>> test('-0')
True
>>> test('+0')
True
>>> test('+1')
True
>>> test('-1-1')
False
>>> test('+1+1')
False
이거 먹어봐요.마이너스 숫자를 입력해도 효과가 있었습니다.
def length(s):
return len(s)
s = input("Enter the string: ")
try:
if (type(int(s))) == int:
print("You input an integer")
except ValueError:
print("it is a string with length " + str(length(s)))
가장 간단한 솔루션은 다음과 같습니다.
a= input("Choose the option\n")
if(int(a)):
print (a);
else:
print("Try Again")
확인 중Decimal
유형:
import decimal
isinstance(x, decimal.Decimal)
다음을 입력할 수 있습니다.
user_input = input("Enter something: ")
if type(user_input) == int:
print(user_input, "Is a number")
else:
print("Not a number")
try:
val = int(user_input)
except ValueError:
print("That's not an int!")
이것은 답변에서 영감을 얻은 것을 바탕으로 합니다.저는 아래와 같이 함수를 정의했습니다.잘 작동하는 것 같습니다.
def isanumber(inp):
try:
val = int(inp)
return True
except ValueError:
try:
val = float(inp)
return True
except ValueError:
return False
a=10
isinstance(a,int) #True
b='abc'
isinstance(b,int) #False
언급URL : https://stackoverflow.com/questions/5424716/how-can-i-check-if-string-input-is-a-number
'programing' 카테고리의 다른 글
행 가져오기의 Oracle 크기를 더 높게 설정하면 앱 속도가 느려집니까? (0) | 2023.06.18 |
---|---|
노드에서 사용자의 IP 주소를 확인하는 방법 (0) | 2023.06.18 |
목록의 키와 값이 0으로 기본 설정된 사전을 만들려면 어떻게 해야 합니까? (0) | 2023.06.18 |
주석과 장식가의 차이점은 무엇입니까? (0) | 2023.06.13 |
Vuex 상태 또는 getter는 항상 정의되지 않은 상태를 반환합니다. (0) | 2023.06.13 |