Nonetype을 정수 또는 문자열로 변환하는 방법은 무엇입니까?
나는 Nonetype
값을 가지고 있으며 x
일반적으로 숫자이지만 None
. 나는 그것을 숫자로 나누고 싶지만 Python은 다음을 발생시킵니다.
TypeError: int() argument must be a string or a number, not 'NoneType'
어떻게 해결할 수 있습니까?
댓글 중 하나에서 다음과 같이 말합니다.
어떻게 든 나는 Nonetype 값을 얻었습니다. 그것은 int이어야하지만 이제는 Nonetype 객체입니다.
그것이 당신의 코드라면, 당신이 None
숫자를 기대할 때 어떻게 얻고 있는지 파악하고 그 일이 발생 하지 않도록하십시오.
다른 사람의 코드 인 None
경우 일반적인 조건부 코드를 사용하여 해당 코드가 제공하는 조건을 찾고이를 위해 사용할 합리적인 값을 결정합니다.
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
...또는...
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
0
여기서 자동으로 사용할 이유는 없습니다 . "거짓"에 의존하는 솔루션은 None
이를 원할 것이라고 가정합니다. 는 DEFAULT_VALUE
(심지어 존재하는 경우) 완전 코드의 목적에 따라 달라집니다.
int(value or 0)
False
None, 0, [], ""등과 같이 Python이 고려하는 값을 제공 할 때 0을 사용합니다 . 0은이므로 False
대체 값으로 0 만 사용해야합니다 (그렇지 않으면 0을 찾을 수 있습니다. 그 값으로 전환).
int(0 if value is None else value)
이것은 None
0으로 만 대체됩니다. None
특별히 테스트 중이므로 대체로 다른 값을 사용할 수 있습니다.
이러한 상황을 처리하는 일반적인 "Pythonic"방법은 EAFP 로 알려져 있습니다. " 허가보다 용서를 구하는 것이 더 쉽습니다 ." 일반적으로 모든 것이 정상이라고 가정하는 코드를 작성 try..except
하고 그렇지 않은 경우 처리 할 수 있도록 블록으로 래핑하는 것을 의미합니다 .
문제에 적용된 코딩 스타일은 다음과 같습니다.
try:
my_value = int(my_value)
except TypeError:
my_value = 0 # or whatever you want to do
answer = my_value / divisor
또는 더 간단하고 약간 더 빠릅니다.
try:
answer = int(my_value) / divisor
except TypeError:
answer = 0
The inverse and more traditional approach is known as LBYL which stands for "Look before you leap" is what @Soviut and some of the others have suggested. For additional coverage of this topic see my answer and associated comments to the question Determine whether a key is present in a dictionary elsewhere on this site.
One potential problem with EAFP is that it can hide the fact that something is wrong with some other part of your code or third-party module you're using, especially when the exceptions frequently occur (and therefore aren't really "exceptional" cases at all).
That TypeError
only appears when you try to pass int()
None
(which is the only NoneType
value, as far as I know). I would say that your real goal should not be to convert NoneType
to int
or str
, but to figure out where/why you're getting None
instead of a number as expected, and either fix it or handle the None
properly.
I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. Sorry, Kindall already gave this answer.
This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.
You should check to make sure the value is not None before trying to perform any calculations on it:
my_value = None
if my_value is not None:
print int(my_value) / 2
Note: my_value
was intentionally set to None to prove the code works and that the check is being performed.
I was having the same problem using the python email functions. Below is the code I was trying to retrieve email subject into a variable. This works fine for most emails and the variable populates. If you receive an email from Yahoo or the like and the sender did no fill out the subject line Yahoo does not create a subject line in the email and you get a NoneType returned from the function. Martineau provided a correct answer as well as Soviut. IMO Soviut's answer is more concise from a programming stand point; not necessarily from a Python one. Here is some code to show the technique:
import sys, email, email.Utils
afile = open(sys.argv[1], 'r')
m = email.message_from_file(afile)
subject = m["subject"]
# Soviut's Concise test for unset variable.
if subject is None:
subject = "[NO SUBJECT]"
# Alternative way to test for No Subject created in email (Thanks for NoneThing Yahoo!)
try:
if len(subject) == 0:
subject = "[NO SUBJECT]"
except TypeError:
subject = "[NO SUBJECT]"
print subject
afile.close()
In Python 3 you can use the "or" keyword too. This way:
foo = bar or 0
foo2 = bar or ""
In some situations it is helpful to have a function to convert None to int zero:
def nz(value):
'''
Convert None to int zero else return value.
'''
if value == None:
return 0
return value
참고URL : https://stackoverflow.com/questions/3930188/how-to-convert-nonetype-to-int-or-string
'programing tip' 카테고리의 다른 글
다른 html이없는 angularjs 개행 필터 (0) | 2020.09.15 |
---|---|
HTTP의 숨겨진 기능 (0) | 2020.09.15 |
1-10 범위의 난수 생성 (0) | 2020.09.14 |
svn diff를 만드는 방법 두 개정 사이에 공백이 아닌 줄 변경 만 표시 (0) | 2020.09.14 |
npm을 사용하여 rubygems 용 번 들러처럼 필수 패키지를 설치하거나 업데이트합니다. (0) | 2020.09.14 |