检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用float
main函数更糟糕.
有没有办法在Python中确定对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
Run Code Online (Sandbox Code Playgroud)
在使用之前如何判断是否a
具有该属性property
?
如何查看变量的类型,无论是无符号32位,带符号16位等等?
我该如何看待它?
这两个代码片段之间有什么区别?使用type()
:
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance()
:
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 我的Google-fu让我失望了.
在Python中,以下两个相等的测试是否等效?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
Run Code Online (Sandbox Code Playgroud)
对于您要比较实例的对象(list
比如说),这是否适用?
好的,所以这样的答案我的问题:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
Run Code Online (Sandbox Code Playgroud)
所以==
测试值测试的地方is
是否是同一个对象?
我正在编写一个必须接受用户输入的程序.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
Run Code Online (Sandbox Code Playgroud)
如果用户输入合理数据,这将按预期工作.
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Run Code Online (Sandbox Code Playgroud)
但如果他们犯了错误,那就崩溃了:
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in …
Run Code Online (Sandbox Code Playgroud) 如何检查Python对象是否为字符串(常规或Unicode)?
python ×10
types ×4
string ×2
16-bit ×1
attributes ×1
casting ×1
equality ×1
inheritance ×1
loops ×1
oop ×1
python-3.x ×1
reference ×1
semantics ×1
signed ×1
unsigned ×1
user-input ×1
validation ×1
variables ×1