Python 如何检查变量是整数还是字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16488278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a variable is an integer or a string?
提问by user2154354
I have an application that has a couple of commands. When you type a certain command, you have to type in additional info about something/someone. Now that info has to be strictly an integer or a string, depending on the situation.
我有一个包含几个命令的应用程序。当您输入某个命令时,您必须输入有关某事/某人的附加信息。现在,该信息必须严格为整数或字符串,具体取决于具体情况。
However, whatever you type into Python using raw_input() actually is a string, no matter what, so more specifically, how would I shortly and without try...except see if a variable is made of digits or characters?
但是,无论您使用 raw_input() 在 Python 中输入什么,实际上都是一个字符串,无论如何,更具体地说,我将如何在不尝试的情况下很快...除了查看变量是由数字还是字符组成?
采纳答案by Martijn Pieters
In my opinion you have two options:
在我看来,您有两种选择:
Just try to convert it to an
int, but catch the exception:try: value = int(value) except ValueError: pass # it was a string, not an int.This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()str.isdigit()returnsTrueonly if all characters in the string are digits (0-9).The
unicode/ Python 3strtype equivalent isunicode.isdecimal()/str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2is a digit, but not a decimal, for example).This is often called the Ask Permission approach, or Look Before You Leap.
只需尝试将其转换为 an
int,但捕获异常:try: value = int(value) except ValueError: pass # it was a string, not an int.这就是请求宽恕的方法。
显式测试字符串中是否只有数字:
value.isdigit()str.isdigit()True仅当字符串中的所有字符都是数字 (0-9)时才返回。的
unicode/ Python的3str型当量unicode.isdecimal()/str.isdecimal(); 只有 Unicode 小数可以转换为整数,因为并非所有数字都有实际的整数值(例如,U+00B2 SUPERSCRIPT 2是数字,但不是小数)。这通常被称为“询问许可”方法,或“跃跃欲试”。
The latter will not detect all valid int()values, as whitespace and +and -are also allowed in int()values. The first form will happily accept ' +10 'as a number, the latter won't.
后者不会检测所有有效值int(),如空格,并且+和-也允许在int()值中。第一种形式很乐意接受' +10 '为数字,后者不会。
If your expect that the user normallywill input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
如果您希望用户通常会输入一个整数,请使用第一种形式。在这种情况下,请求宽恕比请求许可更容易(也更快)。
回答by jwodder
The isdigitmethod of the strtypereturns Trueiff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.
如果给定的字符串只是一个或多个数字isdigit,则该str类型的方法返回True。如果不是,您知道该字符串应该被视为一个字符串。
回答by TehTris
if you want to check what it is:
如果你想检查它是什么:
>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False
if you want to get ints from raw_input
如果你想从 raw_input 获取整数
>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
except: pass
>>>isinstance(x,int)
True
回答by Marcin
Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.
不要检查。继续并假设它是正确的输入,如果不是,则捕获异常。
intresult = None
while intresult is None:
input = raw_input()
try: intresult = int(input)
except ValueError: pass
回答by Alexei Sholik
Depending on your definition of shortly, you could use one of the following options:
根据您对 short 的定义,您可以使用以下选项之一:
try: int(your_input); except ValueError: # ...your_input.isdigit()- use a regex
- use
parsewhich is kind of the opposite offormat
try: int(your_input); except ValueError: # ...your_input.isdigit()- 使用正则表达式
- 使用
parse与format

