try/except를 사용하지 않고 문자열이 int를 나타내는지 확인하려면 어떻게 해야 합니까?
문자열이 정수를 나타내는지 확인할 수 있는 방법이 있습니까(예:'3'
,'-17'
아니다'3.14'
★★★★★★★★★★★★★★★★★」'asfasfas'
★★★★★★★★★★★★★★★★★★★★★★★★★★★★?
is_int('3.14') == False
is_int('-7') == True
양의 정수를 사용할 수 있습니다.
>>> '16'.isdigit()
True
하지만 음의 정수에서는 작동하지 않습니다.다음 사항을 시도해 보겠습니다.
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
'16.0'
.int
그런 의미에서 캐스팅을 하고 있습니다.
편집:
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
try/except
처에있있 있있있다다도우미 기능을 기입해 주세요.
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
Python이 정수로 간주하는 모든 문자열을 정확하게 커버하는 WAY 코드가 될 것입니다.이건 그냥 버마틱하게 하라고 했어.
어떤 이유로든 시도/제외로 모든 것이 잘 수행되지 않는다는 것을 알게 되었습니다(또한 여러 번 테스트했습니다.저는 몇 가지 방법을 시도합니다만, 지금까지 테스트한 방법 중 가장 좋은 것을 실행하는 방법 이외에는 찾아본 적이 없다고 생각합니다.사실 그 방법들은 보통 최악은 아니더라도 최악에 가까운 것으로 보입니다.모든 경우는 아니지만 많은 경우입니다.많은 사람들이 "피토닉" 방식이라고 말하지만, 제가 그들과 헤어지는 한 가지 분야입니다.퍼포먼스도 우아하지도 않기 때문에 에러 트래핑이나 리포트용으로만 사용하는 경향이 있습니다.
PHP, perl, ruby, C, 심지어 빌어먹을 셸까지 문자열의 정수후드를 테스트하기 위한 간단한 함수를 가지고 있다고 불평하려고 했는데, 그러한 전제조건을 검증하기 위한 실사가 나를 혼란스럽게 했다!보아하니 이 결핍은 흔한 병인 것 같다.
Bruno의 투고에 대한 빠르고 지저분한 편집은 다음과 같습니다.
import sys, time, re
g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
testvals = [
# integers
0, 1, -1, 1.0, -1.0,
'0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
# non-integers
'abc 123',
1.1, -1.1, '1.1', '-1.1', '+1.1',
'1.1.1', '1.1.0', '1.0.1', '1.0.0',
'1.0.', '1..0', '1..',
'0.0.', '0..0', '0..',
'one', object(), (1,2,3), [1,2,3], {'one':'two'},
# with spaces
' 0 ', ' 0.', ' .0','.01 '
]
def isInt_try(v):
try: i = int(v)
except: return False
return True
def isInt_str(v):
v = str(v).strip()
return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
def isInt_re(v):
import re
if not hasattr(isInt_re, 'intRegex'):
isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
return isInt_re.intRegex.match(str(v).strip()) is not None
def isInt_re2(v):
return g_intRegex.match(str(v).strip()) is not None
def check_int(s):
s = str(s)
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
def timeFunc(func, times):
t1 = time.time()
for n in range(times):
for v in testvals:
r = func(v)
t2 = time.time()
return t2 - t1
def testFuncs(funcs):
for func in funcs:
sys.stdout.write( "\t%s\t|" % func.__name__)
print()
for v in testvals:
if type(v) == type(''):
sys.stdout.write("'%s'" % v)
else:
sys.stdout.write("%s" % str(v))
for func in funcs:
sys.stdout.write( "\t\t%s\t|" % func(v))
sys.stdout.write("\r\n")
if __name__ == '__main__':
print()
print("tests..")
testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
print()
print("timings..")
print("isInt_try: %6.4f" % timeFunc(isInt_try, 10000))
print("isInt_str: %6.4f" % timeFunc(isInt_str, 10000))
print("isInt_re: %6.4f" % timeFunc(isInt_re, 10000))
print("isInt_re2: %6.4f" % timeFunc(isInt_re2, 10000))
print("check_int: %6.4f" % timeFunc(check_int, 10000))
퍼포먼스 비교 결과는 다음과 같습니다.
timings..
isInt_try: 0.6426
isInt_str: 0.7382
isInt_re: 1.1156
isInt_re2: 0.5344
check_int: 0.3452
C 메서드는 One Through를 스캔하여 실행할 수 있습니다.스트링을 한 번 스캔하는 C 방식이 올바른 방법이라고 생각합니다.
편집:
Python 3.5에서 동작하도록 위의 코드를 업데이트하여 현재 가장 많이 투표된 답변에서 check_int 함수를 포함시키고 정수 후드를 테스트하기 위해 현재 가장 인기 있는 regex를 사용하였습니다.이 정규식은 'abc 123'과 같은 문자열을 거부합니다.테스트 값으로 abc 123을 추가했습니다.
이 시점에서 try 메서드, 일반적인 check_int 함수, 정수 후드를 테스트하기 위한 가장 일반적인 regex 등 테스트된 함수는 모든 테스트 값에 대해 정답을 반환하지 않는다는 것을 알게 되어 매우 흥미롭습니다(정답이 무엇인지에 따라 다릅니다.아래 테스트 결과를 참조하십시오).
삽입 int() 함수는 부동소수점 번호가 최초로 문자열로 변환되지 않는 한 부동소수점 번호의 소수점 부분을 사일런트하게 잘라내고 소수점 이전의 정수 부분을 반환합니다.
check_int() 함수는 0.0 및 1.0(기술적으로는 정수)과 같은 값에 대해 false를 반환하고 '06'과 같은 값에 대해 true를 반환합니다.
현재(Python 3.5) 테스트 결과는 다음과 같습니다.
isInt_try | isInt_str | isInt_re | isInt_re2 | check_int |
0 True | True | True | True | True |
1 True | True | True | True | True |
-1 True | True | True | True | True |
1.0 True | True | False | False | False |
-1.0 True | True | False | False | False |
'0' True | True | True | True | True |
'0.' False | True | False | False | False |
'0.0' False | True | False | False | False |
'1' True | True | True | True | True |
'-1' True | True | True | True | True |
'+1' True | True | True | True | True |
'1.0' False | True | False | False | False |
'-1.0' False | True | False | False | False |
'+1.0' False | True | False | False | False |
'06' True | True | False | False | True |
'abc 123' False | False | False | False | False |
1.1 True | False | False | False | False |
-1.1 True | False | False | False | False |
'1.1' False | False | False | False | False |
'-1.1' False | False | False | False | False |
'+1.1' False | False | False | False | False |
'1.1.1' False | False | False | False | False |
'1.1.0' False | False | False | False | False |
'1.0.1' False | False | False | False | False |
'1.0.0' False | False | False | False | False |
'1.0.' False | False | False | False | False |
'1..0' False | False | False | False | False |
'1..' False | False | False | False | False |
'0.0.' False | False | False | False | False |
'0..0' False | False | False | False | False |
'0..' False | False | False | False | False |
'one' False | False | False | False | False |
<obj..> False | False | False | False | False |
(1, 2, 3) False | False | False | False | False |
[1, 2, 3] False | False | False | False | False |
{'one': 'two'} False | False | False | False | False |
' 0 ' True | True | True | True | False |
' 0.' False | True | False | False | False |
' .0' False | False | False | False | False |
'.01 ' False | False | False | False | False |
방금 이 기능을 추가하려고 했습니다.
def isInt_float(s):
try:
return float(str(s)).is_integer()
except:
return False
check_int(0.3486)와 거의 같은 성능을 발휘하며 1.0, 0.0, +1.0, 0.0 등의 값에 대해 true를 반환합니다.하지만 '06'에 대해서도 true로 반환됩니다.독을 고르는 게 좋을 것 같아
str.isdigit()
효과가 있을 거야
예:
str.isdigit("23") ## True
str.isdigit("abc") ## False
str.isdigit("23.4") ## False
편집: @BuzMoschetti가 지적한 바와 같이 이 방법은 마이너스 번호(예: "-23")에 대해 실패합니다.input_num이 0보다 작을 수 있는 경우 str.isdigit()를 적용하기 전에 re.sub(regex_search, regex_replace, contents)를 사용합니다.예를 들어 다음과 같습니다.
import re
input_num = "-23"
input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
str.isdigit(input_num) ## True
정규 표현 사용:
import re
def RepresentsInt(s):
return re.match(r"[-+]?\d+$", s) is not None
소수점도 허용해야 하는 경우:
def RepresentsInt(s):
return re.match(r"[-+]?\d+(\.0*)?$", s) is not None
성능 정규 을 한 .re.compile()
.
적절한 RegEx 솔루션은 Greg Hewgill과 Nowell의 아이디어를 결합하지만 글로벌 변수를 사용하지 않습니다.이를 위해서는 메서드에 Atribute를 부가합니다.또, 수입에 대해서는 찡그리는 것은 알고 있습니다만, 제가 목표로 하는 것은 http://peak.telecommunity.com/DevCenter/Importing#lazy-imports와 같은 「모듈」의 효과입니다.
편집: 지금까지 제가 가장 좋아했던 기술은 String 오브젝트만의 메서드를 사용하는 것입니다.
#!/usr/bin/env python
# Uses exclusively methods of the String object
def isInteger(i):
i = str(i)
return i=='0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
# Uses re module for regex
def isIntegre(i):
import re
if not hasattr(isIntegre, '_re'):
print("I compile only once. Remove this line when you are confident in that.")
isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$")
return isIntegre._re.match(str(i)) is not None
# When executed directly run Unit Tests
if __name__ == '__main__':
for obj in [
# integers
0, 1, -1, 1.0, -1.0,
'0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0',
# non-integers
1.1, -1.1, '1.1', '-1.1', '+1.1',
'1.1.1', '1.1.0', '1.0.1', '1.0.0',
'1.0.', '1..0', '1..',
'0.0.', '0..0', '0..',
'one', object(), (1,2,3), [1,2,3], {'one':'two'}
]:
# Notice the integre uses 're' (intended to be humorous)
integer = ('an integer' if isInteger(obj) else 'NOT an integer')
integre = ('an integre' if isIntegre(obj) else 'NOT an integre')
# Make strings look like strings in the output
if isinstance(obj, str):
obj = ("'%s'" % (obj,))
print("%30s is %14s is %14s" % (obj, integer, integre))
그리고 모험심이 적은 학급 멤버들을 위한 결과는 다음과 같습니다.
I compile only once. Remove this line when you are confident in that.
0 is an integer is an integre
1 is an integer is an integre
-1 is an integer is an integre
1.0 is an integer is an integre
-1.0 is an integer is an integre
'0' is an integer is an integre
'0.' is an integer is an integre
'0.0' is an integer is an integre
'1' is an integer is an integre
'-1' is an integer is an integre
'+1' is an integer is an integre
'1.0' is an integer is an integre
'-1.0' is an integer is an integre
'+1.0' is an integer is an integre
1.1 is NOT an integer is NOT an integre
-1.1 is NOT an integer is NOT an integre
'1.1' is NOT an integer is NOT an integre
'-1.1' is NOT an integer is NOT an integre
'+1.1' is NOT an integer is NOT an integre
'1.1.1' is NOT an integer is NOT an integre
'1.1.0' is NOT an integer is NOT an integre
'1.0.1' is NOT an integer is NOT an integre
'1.0.0' is NOT an integer is NOT an integre
'1.0.' is NOT an integer is NOT an integre
'1..0' is NOT an integer is NOT an integre
'1..' is NOT an integer is NOT an integre
'0.0.' is NOT an integer is NOT an integre
'0..0' is NOT an integer is NOT an integre
'0..' is NOT an integer is NOT an integre
'one' is NOT an integer is NOT an integre
<object object at 0x103b7d0a0> is NOT an integer is NOT an integre
(1, 2, 3) is NOT an integer is NOT an integre
[1, 2, 3] is NOT an integer is NOT an integre
{'one': 'two'} is NOT an integer is NOT an integre
>>> "+7".lstrip("-+").isdigit()
True
>>> "-7".lstrip("-+").isdigit()
True
>>> "7".lstrip("-+").isdigit()
True
>>> "13.4".lstrip("-+").isdigit()
False
따라서 기능은 다음과 같습니다.
def is_int(val):
return val.lstrip("-+").isdigit()
저는 시도/예외 패턴을 사용하는 것에 대해 약간은 거부감이 있지만 불합리하다는 것은 인정합니다.나는 이것을 사용한다.
all([xi in '1234567890' for xi in x])
음수를 사용할 수 없으므로 왼쪽에 있는 모든 마이너스 기호를 제거한 다음 결과가 0-9의 숫자로 구성되는지 확인할 수 있습니다.
all([xi in '1234567890' for xi in x.lstrip('-')])
입력이 문자열인지 확실하지 않은 경우 x를 str()에 전달할 수도 있습니다.
all([xi in '1234567890' for xi in str(x).lstrip('-')])
(엣지?) 이 문제가 발생하는 경우가 있습니다.
- 다양한 과학적 및/또는 지수 표기법(예: 1.2E3, 10^3 등)에서는 작동하지 않으며 둘 다 False를 반환합니다.3.의견을 왜냐하면 Python 3.8이 Python 3.8은 Python 3.8로 되어 있기 때문입니다.
type(1E2)
<class 'float'>
, 「」입니다.type(10^2)
<class 'int'>
. - 빈 문자열 입력은 True입니다.
- 선행 플러스 기호(예: "+7")는 False를 나타냅니다.
- 여러 개의 마이너스 부호는 선두 문자인 한 무시됩니다. interpreter*와합니다.
type(---1)
<class int>
int('---1')
하지만, 에서는 에러가 반환됩니다.True
같은 입력으로.
따라서 가능한 모든 입력에 대해 작동하지는 않지만, 이러한 입력은 제외할 수 있습니다.False
x가 정수가 아닌 True
x가 정수인 경우.하지만 만약 당신이 정말로 정확히 모범이 되는 행동을 원한다면int()
은 trytry/except를 하는 것이
비단뱀인지는 모르겠지만, 한 줄이고, 암호의 역할은 비교적 명확합니다.
*역사가 선행 마이너스 부호를 무시한다는 것은 아닙니다.선행 마이너스 부호가 몇 개 있어도 결과가 정수라는 것은 변하지 않습니다. int(--1)
-(-1)
1. , 또 11 。int(---1)
라고 -(-(-1))
-1면 되다.따라서 선행 마이너스 부호의 짝수는 양의 정수를, 마이너스 부호의 홀수는 음의 정수를 나타내지만 결과는 항상 정수입니다.
Greg Hewgill의 접근법에는 문자열의 시작 부분에만 일치하는 선두 "^"과 미리 컴파일하는 몇 가지 구성요소가 누락되어 있었습니다.그러나 이 방법을 사용하면 시행을 피할 수 있습니다.
import re
INT_RE = re.compile(r"^[-]?\d+$")
def RepresentsInt(s):
return INT_RE.match(str(s)) is not None
왜 시도를 피하려고 하는지 궁금하네요.
내가 사용하는 가장 쉬운 방법
def is_int(item: str) -> bool:
return item.lstrip('-+').isdigit()
아래 방법으로 확인할 수 있습니다.
def check_if_string_is_int(string1):
for character in string1:
if not character.isdigit():
return "Not a number"
else:
return "Is a number"
생각합니다
s.startswith('-') and s[1:].isdigit()
다음 주소로 다시 쓰는 것이 좋습니다.
s.replace('-', '').isdigit()
s[1:]도 새로운 문자열을 작성하기 때문입니다.
하지만 훨씬 더 나은 해결책은
s.lstrip('+-').isdigit()
Shavais의 투고는 매우 마음에 들었습니다만, 테스트 케이스(& built-in isdigit() 함수)를 하나 더 추가했습니다.
def isInt_loop(v):
v = str(v).strip()
# swapping '0123456789' for '9876543210' makes nominal difference (might have because '1' is toward the beginning of the string)
numbers = '0123456789'
for i in v:
if i not in numbers:
return False
return True
def isInt_Digit(v):
v = str(v).strip()
return v.isdigit()
그리고 그것은 다른 것들의 시간을 크게 앞지릅니다.
timings..
isInt_try: 0.4628
isInt_str: 0.3556
isInt_re: 0.4889
isInt_re2: 0.2726
isInt_loop: 0.1842
isInt_Digit: 0.1577
일반 2.7 python 사용:
$ python --version
Python 2.7.10
추가한 2개의 테스트 케이스(isInt_loop과 isInt_digit)는 모두 동일한 테스트 케이스(둘 다 부호 없는 정수만 받아들임)에 합격했지만, 내장된 isint_loop 함수에 반해 문자열 구현(isInt_loop)을 수정하는 것이 더 현명할 수 있을 것 같아서 포함시켰습니다.time. (두 방법 모두 다른 모든 것을 크게 앞지르지만 추가 정보는 처리하지 마십시오: "/+/-" )
또한 2012년(현재 2018년) Shavais가 실시한 테스트에서 regex(isInt_re2 메서드)가 문자열 비교를 이긴 것도 흥미로웠습니다.정규식 라이브러리가 개선되었을까요?
이것이 아마도 내 생각에 그것에 접근하는 가장 직설적이고 피조적인 방법일 것이다.이 솔루션은 본 적이 없으며 기본적으로 regex와 동일하지만 regex가 없습니다.
def is_int(test):
import string
return not (set(test) - set(string.digits))
에러를 발생시키지 않고 해석하는 기능이 있습니다.명백한 사례 반환을 처리합니다.None
실패 시(CPython에서는 기본적으로 최대 2000개의 '-/+' 기호를 처리합니다!):
#!/usr/bin/env python
def get_int(number):
splits = number.split('.')
if len(splits) > 2:
# too many splits
return None
if len(splits) == 2 and splits[1]:
# handle decimal part recursively :-)
if get_int(splits[1]) != 0:
return None
int_part = splits[0].lstrip("+")
if int_part.startswith('-'):
# handle minus sign recursively :-)
return get_int(int_part[1:]) * -1
# successful 'and' returns last truth-y value (cast is always valid)
return int_part.isdigit() and int(int_part)
일부 테스트:
tests = ["0", "0.0", "0.1", "1", "1.1", "1.0", "-1", "-1.1", "-1.0", "-0", "--0", "---3", '.3', '--3.', "+13", "+-1.00", "--+123", "-0.000"]
for t in tests:
print "get_int(%s) = %s" % (t, get_int(str(t)))
결과:
get_int(0) = 0
get_int(0.0) = 0
get_int(0.1) = None
get_int(1) = 1
get_int(1.1) = None
get_int(1.0) = 1
get_int(-1) = -1
get_int(-1.1) = None
get_int(-1.0) = -1
get_int(-0) = 0
get_int(--0) = 0
get_int(---3) = -3
get_int(.3) = None
get_int(--3.) = 3
get_int(+13) = 13
get_int(+-1.00) = -1
get_int(--+123) = 123
get_int(-0.000) = 0
필요에 따라 다음을 사용할 수 있습니다.
def int_predicate(number):
return get_int(number) is not None
ASCII보다 작은 숫자만 허용하려면 다음 테스트를 수행합니다.
Python 3.7+:(u.isdecimal() and u.isascii())
Python <= 3.6:(u.isdecimal() and u == str(int(u)))
다른 답변은 다음을 제안합니다..isdigit()
또는.isdecimal()
둘 다 대문자를 포함하고 있습니다.'٢'
(u'\u0662'
):
u = u'\u0662' # '٢'
u.isdigit() # True
u.isdecimal() # True
u.isascii() # False (Python 3.7+ only)
u == str(int(u)) # False
전제 조건:
- 우리는 정수에 대해 이야기하고 있다(소수/소수가 아니다).
- 삽입 거동
int()
는 표준입니다(이상할 수 있습니다.-00이 올바른 입력입니다).
간단한 답변:
다음 코드를 사용합니다.단순하고 정확하며(이 스레드의 많은 변형은 그렇지 않지만), 두 가지 모두를 거의 두 배로 능가합니다.try/except
그리고.regex
변종입니다.
def is_int_str(string):
return (
string.startswith(('-', '+')) and string[1:].isdigit()
) or string.isdigit()
TL;DR 답변:
3가지 주요 변형 (1) try/except, (2) re.match() 및 (3) 문자열 연산을 테스트했습니다(위 참조).세 번째 모델은 두 가지 모델보다 약 2배 더 빠릅니다.try/except
그리고.re.match()
. BTW : regex variant가 가장 느리다!아래 테스트 스크립트를 참조하십시오.
import re
import time
def test(func, test_suite):
for test_case in test_suite:
actual_result = func(*test_case[0])
expected_result = test_case[1]
assert (
actual_result == expected_result
), f'Expected: {expected_result} but actual: {actual_result}'
def perf(func, test_suite):
start = time.time()
for _ in range(0, 1_000_000):
test(func, test_suite)
return time.time() - start
def is_int_str_1(string):
try:
int(string)
return True
except ValueError:
return False
def is_int_str_2(string):
return re.match(r'^[\-+]?\d+$', string) is not None
def is_int_str_3(string):
return (
string.startswith(('-', '+')) and string[1:].isdigit()
) or string.isdigit()
# Behavior of built-in int() function is a standard for the following tests
test_suite = [
[['1'], True], # func('1') -> True
[['-1'], True],
[['+1'], True],
[['--1'], False],
[['++1'], False],
[['001'], True], # because int() can read it
[['-00'], True], # because of quite strange behavior of int()
[['-'], False],
[['abracadabra'], False],
[['57938759283475928347592347598357098458405834957984755200000000'], True],
]
time_span_1 = perf(is_int_str_1, test_suite)
time_span_2 = perf(is_int_str_2, test_suite)
time_span_3 = perf(is_int_str_3, test_suite)
print(f'{is_int_str_1.__name__}: {time_span_1} seconds')
print(f'{is_int_str_2.__name__}: {time_span_2} seconds')
print(f'{is_int_str_3.__name__}: {time_span_3} seconds')
출력:
is_int_str_1: 4.314162969589233 seconds
is_int_str_2: 5.7216269969940186 seconds
is_int_str_3: 2.5828163623809814 seconds
int를 전혀 사용하지 않을 가능성이 있으며 문자열이 숫자를 나타내지 않는 한 예외를 발생시키지 않아야 합니다.
float(number)==float(number)//1
수용, 양, 음, 공학적 표기법 등 모든 종류의 문자열에 대해 작동해야 합니다.
다음을 권장합니다.
import ast
def is_int(s):
return isinstance(ast.literal_eval(s), int)
문서에서:
표현식 노드 또는 Python 리터럴 또는 컨테이너 디스플레이를 포함하는 문자열을 안전하게 평가합니다.제공된 문자열 또는 노드는 문자열, 바이트, 숫자, 튜플, 목록, 딕트, 세트, 부울란 및 없음의 Python 리터럴 구조로만 구성될 수 있습니다.
의할 a a a a a a a a a a a a가 점에 .ValueError
Python 리터럴을 구성하지 않는 모든 항목에 대해 호출된 경우 예외입니다.시험/제외의 해결 방법을 묻는 질문이었기 때문에 고바야시-마루 타입의 해결 방법을 가지고 있습니다.
from ast import literal_eval
from contextlib import suppress
def is_int(s):
with suppress(ValueError):
return isinstance(literal_eval(s), int)
return False
¯\_(ツ)_/¯
후 캐스트 이며, 의 첫 문자 은 "정수"입니다.-
★★★★★★★★★★★★★★★★★」+
" " " " "isdigit
isdigit
test = ['1', '12015', '1..2', 'a2kk78', '1.5', 2, 1.24, '-8.5', '+88751.71', '-1', '+7']
확인.
for k,v in enumerate(test):
print(k, v, 'test: ', True if isinstance(v, int) is not False else True if str(v)[0] in ['-', '+'] and str(v)[1:].isdigit() else str(v).isdigit())
결과
0 1 test: True
1 12015 test: True
2 1..2 test: False
3 a2kk78 test: False
4 1.5 test: False
5 2 test: True
6 1.24 test: False
7 -8.5 test: False
8 +88751.71 test: False
9 -1 test: True
10 +7 test: True
int에서 문자열 변환 가능성을 확인하고자 하는 것으로 알고 있습니다.그러기 위해서는 다음 작업을 수행합니다.
- '-'를 0으로 바꿉니다. cos '-'는 숫자가 아니며 '-7'도 int로 변환할 수 있습니다.
- 숫자가 맞는지 확인합니다.
def is_string_convertable_to_int(value: str):
if value.replace('-', '').isdigit():
return True
else:
return False
추신. 이 def를 쉽게 수정하여 float에서 문자열 변환가능성을 확인하실 수 있습니다. replace .' ' , ' ) , ' ) , check 、 ' 1 ) = 1 。
시행/제외에는 시간 벌칙이 있기 때문에 질문은 속도와 관련이 있는 것 같습니다.
테스트 데이터
먼저 200개의 문자열, 100개의 실패한 문자열 및 100개의 숫자 문자열 목록을 만들었습니다.
from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)
numpy 솔루션(어레이 및 Unicode에서만 사용 가능)
np 문자열 np.core.defcharararray.isnumeric과도 할 수 .np.core.defchararray.isnumeric(u'+12')
하다따라서 수천 번의 변환을 수행해야 하며 누락된 데이터나 숫자 이외의 데이터가 있는 경우 이 솔루션이 적합합니다.
import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop
시도/제외
def check_num(s):
try:
int(s)
return True
except:
return False
def check_list(l):
return [check_num(e) for e in l]
%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop
숫자 솔루션이 훨씬 빠른 것 같습니다.
어.. 이거 먹어봐
def int_check(a):
if int(a) == a:
return True
else:
return False
숫자가 아닌 문자열을 입력하지 않으면 이 기능이 있습니다.
그리고 (번호체크 부분을 넣는 것을 잊었습니다) 문자열이 숫자인지 아닌지를 확인하는 기능이 있습니다.str.isdigit() 입니다.다음은 예를 제시하겠습니다.
a = 2
a.isdigit()
a.isdigit()를 호출하면 True가 반환됩니다.
언급URL : https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except
'programing' 카테고리의 다른 글
MYSQL phmyadmin 사용자 계정 업데이트/추가 오류 (0) | 2022.11.08 |
---|---|
클릭하우스, 고속 가입을 위한 엔진 (0) | 2022.11.08 |
리셋 세트개체로부터의 간격() (0) | 2022.11.08 |
투고 요청의 크기 제한은 얼마입니까? (0) | 2022.11.08 |
JavaScript를 사용하여 새 페이지를 로드하지 않고 브라우저에서 URL 변경 (0) | 2022.11.08 |