Python에서 try/except를 사용하여 문자열을 Int로 변환
그래서 저는 try/except 함수를 사용하여 문자열을 int로 변환하는 방법에 대해 꽤 당황스럽습니다.이것을 어떻게 하는지 간단한 기능을 아는 사람이 있습니까?저는 아직 현악기와 인트에 대해 약간 흐리멍덩한 느낌이 듭니다.저는 int가 숫자와 관련이 있다고 꽤 확신합니다.문자열...별로.
시도/제외 블록을 사용할 때 어떤 예외를 잡으려고 하는지 구체적으로 설명하는 것이 중요합니다.
string = "abcd"
try:
string_int = int(string)
print(string_int)
except ValueError:
# Handle the exception
print('Please enter an integer')
시도/예외는 여러 가지 방법으로 실패할 수 있는 경우 각 실패 사례에서 프로그램이 어떻게 반응하도록 할지 지정할 수 있기 때문에 강력합니다.
여기 있습니다.
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
첫째, /는 함수가 아니라 문입니다.
Python에서 문자열(또는 변환할 수 있는 다른 유형)을 정수로 변환하려면 기본 제공 함수를 호출하기만 하면 됩니다. int()
할 것이다raise
a 실패할 경우 이를 구체적으로 파악해야 합니다.
Python 2.x의 경우:
>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
... try:
... print '%s as an int is %d' % (str(value), int(value))
... except ValueError as ex:
... print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
Python 3.x에서
구문이 약간 변경되었습니다.
>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
... try:
... print('%s as an int is %d' % (str(value), int(value)))
... except ValueError as ex:
... print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
대부분의 경우 사용자로부터 정수 값을 가져오려고 합니다.사용자는 주의해야 할 정수가 아닌 값을 삽입할 수 있으며 다시 시도하라는 메시지가 표시됩니다.다음 스니펫을 사용하여 사용자로부터 정수 값을 가져오고 유효한 정수를 넣을 때까지 정수를 삽입하라는 메시지를 계속 표시할 수 있습니다.
def get_integer_value():
user_value = input("Enter an integer: ")
try:
return int(user_value)
except ValueError:
print(f"{user_value} is not a valid integer. Please try again.")
return get_integer_value()
if __name__ == "__main__":
print(f"You have inserted: {get_integer_value()}")
출력:
Enter an integer: asd
asd is not a valid integer. Please try again.
Enter an integer: 32
You have inserted: 32
할 수 있는 일:
try :
string_integer = int(string)
except ValueError :
print("This string doesn't contain an integer")
불행히도 공식 문서는 다음과 같은 예외에 대해 많은 것을 말하지 않습니다.int()
올릴 수 있습니다. 그러나 사용할 때int()
기본적으로 두 가지 예외가 발생할 수 있습니다.TypeError
값이 숫자 또는 문자열(또는 바이트 또는 바이트 배열)이 아닌 경우,ValueError
값이 실제로 숫자에 매핑되지 않는 경우.
다음과 같은 방법으로 두 가지를 모두 관리해야 합니다.
try:
int_value = int(value)
except (TypeError, ValueError):
print('Not an integer')
언급URL : https://stackoverflow.com/questions/8075877/converting-string-to-int-using-try-except-in-python
'programing' 카테고리의 다른 글
현재 버전과 마지막 버전 간의 차이 찾기 (0) | 2023.05.14 |
---|---|
javascript 실행 시 mongodb 콘솔에 쓸 수 있습니까? (0) | 2023.05.14 |
모서리가 둥글고 그림자가 드리워진 UIView? (0) | 2023.05.14 |
Postgre에서 특정 행 내보내기SQL 테이블을 INSERT SQL 스크립트로 사용 (0) | 2023.05.14 |
os.path.join에 대한 Pathlib 대안이 있습니까? (0) | 2023.05.14 |